您的位置:首页 > 科技 > 能源 > websocket的demo

websocket的demo

2024/12/28 2:06:07 来源:https://blog.csdn.net/qq_59348245/article/details/141224131  浏览:    关键词:websocket的demo

1.引入依赖

		<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-websocket</artifactId></dependency>

2.前端代码

<!DOCTYPE html>
<html lang="en">
<head><meta charset="UTF-8"><title>Title</title>
</head>
<body><h1>12</h1>
<script>var websocket = null;if ('WebSocket' in window){websocket = new WebSocket('ws://localhost:8080/webSocket');}else {alert("不支持websocket ")}websocket.onopen = function (event){console.log('建立连接')}websocket.onclose = function (event){console.log('连接关闭')}websocket.onmessage = function (event){console.log('收到消息'+event.data)}websocket.onerror = function (){alert('错误')}window.onbeforeunload = function (){websocket.close();}
</script>
</body>
</html>

3.后端代码

@Component
public class WebConfig {@Beanpublic ServerEndpointExporter serverEndpointExporter(){return new ServerEndpointExporter();}
}@Component
@ServerEndpoint("/webSocket")
public class WebSocket {private Session session;private static CopyOnWriteArraySet<WebSocket> webSockets = new CopyOnWriteArraySet<>();@OnOpenpublic void onOpen(Session session){this.session = session;webSockets.add(this);System.out.println("webSocket消息,有新的连接 总数" + webSockets.size());}@OnClosepublic void onClose(){this.session = session;webSockets.remove(this);System.out.println("webSocket消息,连接断开 总数" + webSockets.size());}@OnMessagepublic void onMessage(String message){System.out.println("客户端消息" + message);}public void sendMessage(String message){for (WebSocket webSocket : webSockets) {System.out.println("广播消息" + message);try {webSocket.session.getBasicRemote().sendText(message);} catch (IOException e) {e.printStackTrace();}}}
}

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com