1、Java8+Tomcat8。
package com.ssm.cts.websocket; import javax.websocket.CloseReason; import javax.websocket.OnClose; import javax.websocket.OnError; import javax.websocket.OnMessage; import javax.websocket.OnOpen; import javax.websocket.RemoteEndpoint; import javax.websocket.Session; import javax.websocket.server.ServerEndpoint; import org.apache.log4j.Logger; import java.nio.*; import java.util.*; /** * CopyRright (c)2018-2028: chanpinxue.cn * Project: cts * Module Name: CtsWebSocket * Comments: WebSocket服务端 * JDK version used: JDK1.8 * Author: jzh * Create Date: 2018-11-04 * Modified By: jzh * Modified Date: 2018-11-04 * Why & What is modified: * Version: <1.0> */ // 注解@ServerEndpoint表示它是一个WebSocket服务端 @ServerEndpoint(value="/ctsWebSocket") public class CtsWebSocket { protected final Logger logger = Logger.getLogger(CtsWebSocket.class); static List<Session> clientList = Collections.synchronizedList(new ArrayList<Session>()); // 注解@OnOpen表示它在客户端连接时发生 @OnOpen public void start(Session session) { // 每当有客户端连接进来时,收集该客户对应的session clientList.add(session); logger.info("客户端连接:" + session.getBasicRemote()); } // 注解@OnMessage表示它在客户端消息到达时发生 @OnMessage public void message(String message, Session session) throws Exception { // 收到消息后,将消息向所有客户发送一次 logger.info("客户端消息:" + message); for (Session s : clientList) { RemoteEndpoint.Basic remote = s.getBasicRemote(); remote.sendText(message); } } // 注解@OnClose表示它在客户端连接关闭时发生 @OnClose public void end(Session session, CloseReason closeReason) { // 每当有客户连接关闭时,删除该客户对应的session clientList.remove(session); } // 注解@OnError表示它在客户端出错时发生 @OnError public void error(Session session, Throwable throwable) { // 每当有客户连接出错时,删除该客户对应的session clientList.remove(session); } }
2、websocket.html
<!DOCTYPE html> <html> <head> <title>WebSocket</title> <style> html, body { font: normal 1em arial, helvetica; } #log { width: 400px; height: 200px; border: 1px solid #000000; overflow: auto; } #msg { width: 330px; } </style> <script> var socket; function init() { var host = "ws://127.0.0.1:8080/cts/ctsWebSocket"; //var host = "ws://127.0.0.1:8081/"; try { socket = new WebSocket(host); socket.onopen = function (msg) { log("Begin Connection!"); }; socket.onmessage = function (msg) { log(msg.data); }; socket.onclose = function (msg) { log("Lose Connection!"); }; } catch (ex) { log(ex); } $("msg").focus(); } function send() { var txt, msg; txt = $("msg"); msg = txt.value; if (!msg) { alert("Message can not be empty"); return; } txt.value = ""; txt.focus(); try { socket.send(msg); } catch (ex) { log(ex); } } window.onbeforeunload = function () { try { socket.send('quit'); socket.close(); socket = null; } catch (ex) { log(ex); } }; function $(id) { return document.getElementById(id); } function log(msg) { $("log").innerHTML += "<br>" + msg; } function onkey(event) { if (event.keyCode == 13) { send(); } } </script> </head> <body onload="init()"> <h3>WebSocket</h3> <br> <div id="log"></div> <input id="msg" type="textbox" onkeypress="onkey(event)"/> <button onclick="send()">发送</button> </body> </html>
3、打开两个websocket.html,进行数据交互测试。