1、相关概念原理
懒得写了,这里有介绍:https://my.oschina.net/kdy1994/blog/809802
2、WebSocket生命周期
- 打开:@OnOpen;void方法,可选带参数一个Session、一个EndPointConfig、任意多个@PathParam
- 消息:@OnMessage;方法参数一个Session、一个EndPointConfig、任意多个@PathParam、消息、分片标志位(Boolean,true-最后;false-非)
消息类型
*文本消息:String、Reader
*二进制:ByteBuffer、byte[]、InputStream
pong消息:PongMessage接口实例
返回类型
void:
非 void:会将返回值发送给消息的发送者。 - 错误:@OnError:可带错误消息Throwable、Session、多个@PathParam
- 关闭:@OnClose:可带关闭信息CloseReason、Session、多个@PathParam
3、WebSocket的应用与实现
最新的一个项目中因为要控制用户只能在一个地方登陆,及时显示登录情况信息,就是用的WebSocket实现的
服务端实现
@EnableWebSocket 声明该类支持WebSocket
/** * @ServerEndpoint 注解是一个类层次的注解,它的功能主要是将目前的类定义成一个websocket服务器端, * 注解的值将被用于监听用户连接的终端访问URL地址,客户端可以通过这个URL来连接到WebSocket服务器端 */ @ServerEndpoint("/websocket/{tstr}") public class WebSocketForJSP { //concurrent包的线程安全Set,用来存放每个客户端对应的MyWebSocket对象。若要实现服务端与单一客户端通信的话,可以使用Map来存放,其中Key可以为用户标识 public static CopyOnWriteArraySet<WebSocketForJSP> webSocketSet = new CopyOnWriteArraySet<WebSocketForJSP>(); //与某个客户端的连接会话,需要通过它来给客户端发送数据 private Session session; // 登录用户名 public String userName; //所属IP public String ip; /** * 连接建立成功调用的方法 * @param session 可选的参数。session为与某个客户端的连接会话,需要通过它来给客户端发送数据 */ @OnOpen public void onOpen(@PathParam("tstr") String tstr, Session session){ String[] str = tstr.split(","); this.userName = str[0]; this.ip = str[1]; this.session = session; Boolean isIn = false; for (WebSocketForJSP socket : WebSocketForJSP.webSocketSet) { if(userName.equals(socket.userName) && ip.equals(socket.ip)){ isIn = true; System.out.println("websocket已经连接:"+userName+" "+ip); //删除老的,新增新的 webSocketSet.remove(socket); webSocketSet.add(this); break; } } if(! isIn){ webSocketSet.add(this); //加入set中 System.out.println("有新连接加入!当前在线人数为" + getOnlineCount()); } } /** * 连接关闭调用的方法 */ @OnClose public void onClose(){ webSocketSet.remove(this); //从set中删除 System.out.println("有一连接关闭!当前在线人数为" + getOnlineCount()); } /** * 收到客户端消息后调用的方法 * @param message 客户端发送过来的消息 * @param session 可选的参数 */ @OnMessage public void onMessage(String message, Session session) { System.out.println("来自客户端的消息:" + message); /* try { this.sendMessage("服务器回复消息:"+this.userName); } catch (IOException e) { e.printStackTrace(); } */ } /** * 发生错误时调用 * @param session * @param error */ @OnError public void onError(Session session, Throwable error){ System.out.println("发生错误"); this.onClose(); error.printStackTrace(); } /** * 这个方法与上面几个方法不一样。没有用注解,是根据自己需要添加的方法。 * @param message * @throws IOException */ public void sendMessage(String message) throws IOException{ System.out.println("返回结果----------------->:"+message); this.session.getAsyncRemote().sendText(message); //this.session.getAsyncRemote().sendText(message); } public static synchronized int getOnlineCount() { return WebSocketForJSP.webSocketSet.size(); } }
//然后在用户登录的地方判断即可
// 判断是否已经登录 for(WebSocketForJSP item: WebSocketForJSP.webSocketSet){ if(item.userName.equals(userName)){ return "用户已在其他电脑登录!"; } String userIp = IpUtils.getIpAddr(request); if(item.ip.equals(userIp)){ return "同一段IP只允许登陆一个用户"; } }
客户端调用
/** * 推送 用户java获取用户信息 */ function sendWebSocketMsg(){ //判断当前浏览器是否支持WebSocket // var test = window.location.host; // var IP = test.split(":"); var tstr = userName +","+localIP if ('WebSocket' in window) { //此处参数只允许字符串,不支持json websocket = new WebSocket(getRootPath().replace("http","ws")+"/websocket/"+tstr); } //连接发生错误的回调方法 websocket.onerror = function () { websocket.close(); }; //连接成功建立的回调方法 websocket.onopen = function () { //setInterval(function(){ websocket.send(tstr); //}, 10 * 1000); } //监听窗口关闭事件,当窗口关闭时,主动去关闭websocket连接,防止连接还没断开就关闭窗口,server端会抛异常。 window.onbeforeunload = function () { websocket.close(); } //接收到消息的回调方法 websocket.onmessage = function (event) { try { var result = JSON.parse(event.data); // 是否是对象 if(typeof(result) == "object" && Object.prototype.toString.call(result).toLowerCase() == "[object object]" && !result.length){ if(result.msgType != null && typeof(result.msgType) != "undefined"){ // 负载-自动化运维 debugger; window.showScriptDiagle(result); }else{ debugger; // 回显健康-运维经验 $(window.frames[0])[0].doScriptFn(result); } } } catch (e) { if("logOut" == event.data){ websocket.close(); sessionStorage.setItem("oneUser",true); location.href = getRootPath()+"/jsps/login/login.jsp"; }else if("logOutByIp" == event.data){ websocket.close(); sessionStorage.setItem("oneIp",true); location.href = getRootPath()+"/jsps/login/login.jsp"; } } console.log(event.data); } //连接关闭的回调方法 websocket.onclose = function () { websocket.close(); } }