一、前端页面
<!DOCTYPE html>
<html lang="en">
<head><meta charset="UTF-8"><title>webSocket</title><style type="text/css"></style>
</head>
<body>
<h1>WebSocket</h1>
<input type="button" onclick="websocket.send('666666666')" value="点我发消息"/>
</body>
<script type="application/javascript">var websocket = {send: function (str) {}};window.onload = function () {if (!'WebSocket' in window) return;webSocketInit();};function webSocketInit() {websocket = new WebSocket("ws://localhost:8081//websocket/socket");//成功建立连接websocket.onopen = function () {websocket.send("成功连接到服务器");};//接收到消息websocket.onmessage = function (event) {console.log(event.data)};//连接发生错误websocket.onerror = function () {alert("WebSocket连接发生错误");};//连接关闭websocket.onclose = function () {alert("WebSocket连接关闭");};//监听窗口关闭事件,当窗口关闭时,主动关闭websocket连接window.onbeforeunload = function () {websocket.close()};}
</script>
</html>
二、后端代码
2.1 maven引入
<!--websocket--><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-websocket</artifactId></dependency>
2.2 配置类
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.socket.config.annotation.EnableWebSocket;
import org.springframework.web.socket.server.standard.ServerEndpointExporter;@Configuration
@EnableWebSocket
public class WebSocketConfig {@Beanpublic ServerEndpointExporter serverEndpointExporter() {return new ServerEndpointExporter();}}
2.3 接收实现类
import org.springframework.stereotype.Component;import javax.websocket.*;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.concurrent.CopyOnWriteArraySet;@Component
@ServerEndpoint("/websocket/socket") //暴露的ws应用的路径
public class WebSocket {//concurrent包下线程安全的Setprivate static final CopyOnWriteArraySet<WebSocket> SESSIONS = new CopyOnWriteArraySet<>();private Session session;@OnOpenpublic void onOpen(Session session) {this.session = session;SESSIONS.add(this);System.out.println(String.format("成功建立连接~ 当前总连接数为:%s", SESSIONS.size()));System.out.println(this);}@OnClosepublic void onClose() {SESSIONS.remove(this);System.out.println(String.format("成功关闭连接~ 当前总连接数为:%s", SESSIONS.size()));}@OnMessagepublic void onMessage(String message, Session session) {System.out.println(message);}@OnErrorpublic void onError(Session session, Throwable error) {System.out.println("发生错误");error.printStackTrace();}/*** 指定发消息** @param message*/public void sendMessage(String message) {try {this.session.getBasicRemote().sendText(message);} catch (IOException e) {e.printStackTrace();}}/*** 群发消息** @param message*/public static void fanoutMessage(String message) {SESSIONS.forEach(ws -> ws.sendMessage(message));}
}