WebSocket
webSocket是基于TCP的一种新的网络协议。他实习了浏览器与服务器全双工通信—浏览器和服务器只需要完成一次握手,两者之间就可以创建持久性的连接,并进行双向数据传输
解析
当前端发送请求websocket.send(message); 后端的@onMessage方法会被调用,当后端session.getBasicRemote().sendText(message);发送请求,前端的 websocket.onmessage 回被调用
前端
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69
| <!DOCTYPE HTML> <html> <head> <meta charset="UTF-8"> <title>WebSocket Demo</title> </head> <body> <input id="text" type="text" /> <button onclick="send()">发送消息</button> <button onclick="closeWebSocket()">关闭连接</button> <div id="message"> </div> </body> <script type="text/javascript"> var websocket = null; var clientId = Math.random().toString(36).substr(2);
if('WebSocket' in window){ websocket = new WebSocket("ws://localhost:8080/ws/"+clientId); } else{ alert('Not support websocket') }
websocket.onerror = function(){ setMessageInnerHTML("error"); };
websocket.onopen = function(){ setMessageInnerHTML("连接成功"); }
websocket.onmessage = function(event){ setMessageInnerHTML(event.data); }
websocket.onclose = function(){ setMessageInnerHTML("close"); }
window.onbeforeunload = function(){ websocket.close(); }
function setMessageInnerHTML(innerHTML){ document.getElementById('message').innerHTML += innerHTML + '<br/>'; }
function send(){ var message = document.getElementById('text').value; websocket.send(message); } function closeWebSocket() { websocket.close(); } </script> </html>
|
java代码
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75
| package com.sky.websocket;
import org.springframework.stereotype.Component; import javax.websocket.OnClose; import javax.websocket.OnMessage; import javax.websocket.OnOpen; import javax.websocket.Session; import javax.websocket.server.PathParam; import javax.websocket.server.ServerEndpoint; import java.util.Collection; import java.util.HashMap; import java.util.Map;
@Component @ServerEndpoint("/ws/{sid}") public class WebSocketServer {
private static Map<String, Session> sessionMap = new HashMap();
@OnOpen public void onOpen(Session session, @PathParam("sid") String sid) { System.out.println("客户端:" + sid + "建立连接"); sessionMap.put(sid, session); }
@OnMessage public void onMessage(String message, @PathParam("sid") String sid) { String mes = "收到来自客户端:" + sid + "的信息:" + message; System.out.println("收到来自客户端:" + sid + "的信息:" + message); sendToAllClient(mes); }
@OnClose public void onClose(@PathParam("sid") String sid) { System.out.println("连接断开:" + sid); sessionMap.remove(sid); }
public void sendToAllClient(String message) { Collection<Session> sessions = sessionMap.values(); for (Session session : sessions) { try { session.getBasicRemote().sendText(message); } catch (Exception e) { e.printStackTrace(); } } }
}
|
配置
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
| package com.sky.config;
import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.web.socket.server.standard.ServerEndpointExporter;
@Configuration public class WebSocketConfiguration {
@Bean public ServerEndpointExporter serverEndpointExporter() { return new ServerEndpointExporter(); }
}
|
聊天接口
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115
| package cn.liuzhengquan.instantmessageuserinterfaceservice.controller;
import cn.liuzhengquan.instantmessageuserinterfaceservice.entity.Friends; import cn.liuzhengquan.instantmessageuserinterfaceservice.entity.Messages; import com.alibaba.fastjson.JSON; import lombok.extern.slf4j.Slf4j; import org.springframework.stereotype.Component; import org.springframework.util.StringUtils;
import javax.websocket.OnClose; import javax.websocket.OnMessage; import javax.websocket.OnOpen; import javax.websocket.Session; import javax.websocket.server.PathParam; import javax.websocket.server.ServerEndpoint; import java.io.IOException; import java.util.ArrayList; import java.util.List; import java.util.concurrent.ConcurrentHashMap;
@Slf4j @Component @ServerEndpoint(value = "/websocket/{nickname}") public class WebSocketController { private Session session;
public static List<Friends> friendsList = new ArrayList<>();
public static ConcurrentHashMap<String, WebSocketController> webSocketSession = new ConcurrentHashMap<>();
@OnOpen public void onOpen(@PathParam(value = "nickname") String nickname, Session session) { this.session = session; webSocketSession.put(nickname, this); friendsList.add(Friends.builder().nickname(nickname).build()); updateFriendInformationList(); log.info("【WebSocket消息】有新的连接[{}], 连接总数:{}", nickname, webSocketSession.size()); }
private synchronized void updateFriendInformationList() { webSocketSession.forEach((key, val) -> { List<Friends> friends = new ArrayList<>(); friendsList.forEach((friend) -> { if (!friend.getNickname().equals(key)) { friends.add(friend); } }); sendP2PMessage(key, JSON.toJSONString(Messages.builder().type("updateFriendsList").receiveNickname(key).messages(friends).build())); }); }
@OnMessage public void onMessage(@PathParam(value = "nickname") String nickname, String message) { log.info("【WebSocket消息】 收到客户端[{}] 发送消息:{} 连接总数:{}", nickname, message, webSocketSession.size()); if (StringUtils.hasLength(message)) { try { Messages messages = JSON.parseObject(message, Messages.class); sendP2PMessage(messages.getReceiveNickname(), message); } catch (Exception e) { log.error("WebSocket消息异常:", e); } } }
@OnClose public void onClose(@PathParam(value = "nickname") String nickname) { friendsList.remove(friendsList.stream().filter((friends -> friends.getNickname().equals(nickname))).findAny().orElse(null)); webSocketSession.remove(nickname); updateFriendInformationList(); log.info("【WebSocket消息】客户端[{}]连接断开, 剩余连接总数:{}", nickname, webSocketSession.size()); }
public static synchronized void sendP2PMessage(String nickname, String message) { log.info("【WebSocket消息】点对点发送消息, nickname={} , message={}", nickname, message); try { webSocketSession.get(nickname).session.getBasicRemote().sendText(message); } catch (IOException e) { log.error("点对点发送异常:", e); } }
}
|