WebSockets 彻底改变了 Web,将笨拙、缓慢的实时交互转变为时尚、低延迟的体验,使其成为动态、用户友好型应用程序的首选。
在Intellij IDEA工具中使用SpringBoot项目初始化向导新建一个工程,如工程名为
yuan-websocket-demo
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<parent>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-starter-parentartifactId>
<version>2.3.0.RELEASEversion>
parent>
<modelVersion>4.0.0modelVersion>
<artifactId>yuan-websocket-demoartifactId>
<dependencies>
<dependency>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-starter-websocketartifactId>
dependency>
<dependency>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-starter-thymeleafartifactId>
dependency>
<dependency>
<groupId>com.alibabagroupId>
<artifactId>fastjsonartifactId>
<version>1.2.68version>
dependency>
dependencies>
project>
server:
port: 2001
max-http-header-size: 8192
spring:
thymeleaf:
cache: false
主启动类中标注开启WebSoket的注解
@EnableWebSocket
package org.yuan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.web.servlet.ServletComponentScan;
import org.springframework.web.socket.config.annotation.EnableWebSocket;
/**
*
* Description:
*
* Author:jinshengyuan
* Datetime: 2020-05-29 15:00
*
*
*/
@SpringBootApplication
@EnableWebSocket
@ServletComponentScan
public class MyWebSocketApplication {
public static void main(String[] args) {
SpringApplication.run(MyWebSocketApplication.class, args);
}
}
package org.yuan.mysoket;
import org.springframework.stereotype.Component;
import javax.websocket.*;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.concurrent.CopyOnWriteArraySet;
@Component
@ServerEndpoint("/myChat")
public class MyWebSocket {
private static int onLineCount = 0;//记录在线连接数,应该做成线程安全的
//线程安全set,用来存储每个客户的MyWebSocket对象
private static CopyOnWriteArraySet<MyWebSocket> myWebSockets = new CopyOnWriteArraySet<>();
//与某个客户端的连接会话,需要通过它来给客户发送数据
private Session session;
/**
*
* Description: 连接建立成功后调用的方法
*
* Author:jinshengyuan
* Datetime: 2020/5/28 22:25
*
*
* @return
* @since 2020/5/28 22:25
*/
@OnOpen
public void onOpen(Session session) {
System.out.println("连接了哦");
this.session = session;
myWebSockets.add(this);
addOnlineCount();
System.out.println();
}
/**
*
* Description: 关闭会话连接
*
* Author:jinshengyuan
* Datetime: 2020/5/28 22:39
*
*
* @param
* @param
* @return
* @since 2020/5/28 22:39
*/
@OnClose
public void onClose(Session session) {
myWebSockets.remove(this);
subOnlineCount();
}
/**
*
* Description: 发送消息
*
* Author:jinshengyuan
* Datetime: 2020/5/28 22:39
*
* @since 2020/5/28 22:39
*/
@OnMessage
public void onMessage(String message, Session session) {
System.out.println("来自客户端的消息:" + message);
for (MyWebSocket socket : myWebSockets) {
try {
socket.sendMessage(message);
} catch (IOException e) {
e.printStackTrace();
continue;
}
}
}
public void sendMessage(String message) throws IOException {
this.session.getBasicRemote().sendText(message);
}
@OnError
public void onError(Session session, Throwable error) {
System.out.println("发送消息失败");
error.printStackTrace();
}
public static synchronized void addOnlineCount() {
MyWebSocket.onLineCount++;
}
public static synchronized void subOnlineCount() {
MyWebSocket.onLineCount--;
}
public static synchronized int getOnLineCount() {
return onLineCount;
}
}
index.html如下
<html><head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>web_sockettitle>
<script type="text/javascript">
var ws;
function init() {
// Connect to Web Socket.
// Change host/port here to your own Web Socket server.
ws = new WebSocket("ws://localhost:2001/myChat");
// Set event handlers.
ws.onopen = function() {
output("onopen");
};
ws.onmessage = function(e) {
// e.data contains received string.
output("onmessage: " + e.data);
};
ws.onclose = function() {
output("onclose");
};
ws.onerror = function() {
output("onerror");
};
}
function onSubmit() {
var input = document.getElementById("input");
// You can send message to the Web Socket using ws.send.
ws.send(input.value);
output("send: " + input.value);
input.value = "";
input.focus();
}
function onCloseClick() {
ws.close();
}
function output(str) {
var log = document.getElementById("log");
var escaped = str.replace(/&/, "&").replace(/</, "<").
replace(/>/, ">").replace(/"/, """); // "
log.innerHTML = escaped + "
" + log.innerHTML;
}
script>
head>
<body onload="init();">
<form onsubmit="onSubmit(); return false;">
<input type="text" id="input">
<input type="submit" value="Send">
<button onclick="onCloseClick(); return false;">closebutton>
form>
<div id="log">div>
body>html>
启动SpringBoot应用后,浏览器中输入地址进行测试:http://localhost:2001