websocket 实现群聊和私聊的功能

您所在的位置:网站首页 websocket耗资源么 websocket 实现群聊和私聊的功能

websocket 实现群聊和私聊的功能

2023-03-25 01:52| 来源: 网络整理| 查看: 265

WebSocket介绍

WebSocket是一种在单个TCP连接上进行全双工通信的协议。WebSocket通信协议于2011年被IETF定为标准RFC 6455,并由RFC7936补充规范。WebSocket API也被W3C定为标准。

WebSocket使得客户端和服务器之间的数据交换变得更加简单,允许服务端主动向客户端推送数据。在WebSocket API中,浏览器和服务器只需要完成一次握手,两者之间就直接可以创建持久性的连接,并进行双向数据传输。

 

背景

现在,很多网站为了实现推送技术,所用的技术都是轮询。轮询是在特定的的时间间隔(如每1秒),由浏览器对服务器发出HTTP请求,然后由服务器返回最新的数据给客户端的浏览器。这种传统的模式带来很明显的缺点,即浏览器需要不断的向服务器发出请求,然而HTTP请求可能包含较长的头部,其中真正有效的数据可能只是很小的一部分,显然这样会浪费很多的带宽等资源。

而比较新的技术去做轮询的效果是Comet。这种技术虽然可以双向通信,但依然需要反复发出请求。而且在Comet中,普遍采用的长链接,也会消耗服务器资源。

在这种情况下,HTML5定义了WebSocket协议,能更好的节省服务器资源和带宽,并且能够更实时地进行通讯。

 

简单来说就是:之前在HTTP协议时想要实现推送也就是所谓的客户端服务端长连接,客户端接收服务端消息。就是需要客户端每隔一段较短的时间去向服务端发送请求。这样由于http头较长,所以会浪费较多的带宽资源。所以定义了一种新的协议WebSocket去替代这种“长连接”。

 

WebSocket协议

WebSocket并不是全新的协议,而是利用了HTTP协议来建立连接。我们来看看WebSocket连接是如何创建的。

首先,WebSocket连接必须由浏览器发起,因为请求协议是一个标准的HTTP请求,格式如下:

GET ws://localhost:3000/ws/chat HTTP/1.1 Host: localhost Upgrade: websocket Connection: Upgrade Origin: http://localhost:3000 Sec-WebSocket-Key: client-random-string Sec-WebSocket-Version: 13

该请求和普通的HTTP请求有几点不同:

GET请求的地址不是类似/path/,而是以ws://开头的地址;请求头Upgrade: websocket和Connection: Upgrade表示这个连接将要被转换为WebSocket连接;Sec-WebSocket-Key是用于标识这个连接,并非用于加密数据;Sec-WebSocket-Version指定了WebSocket的协议版本。

随后,服务器如果接受该请求,就会返回如下响应:

HTTP/1.1 101 Switching Protocols Upgrade: websocket Connection: Upgrade Sec-WebSocket-Accept: server-random-string

该响应代码101表示本次连接的HTTP协议即将被更改,更改后的协议就是Upgrade: websocket指定的WebSocket协议。

版本号和子协议规定了双方能理解的数据格式,以及是否支持压缩等等。如果仅使用WebSocket的API,就不需要关心这些。

现在,一个WebSocket连接就建立成功,浏览器和服务器就可以随时主动发送消息给对方。消息有两种,一种是文本,一种是二进制数据。通常,我们可以发送JSON格式的文本,这样,在浏览器处理起来就十分容易。

为什么WebSocket连接可以实现全双工通信而HTTP连接不行呢?实际上HTTP协议是建立在TCP协议之上的,TCP协议本身就实现了全双工通信,但是HTTP协议的请求-应答机制限制了全双工通信。WebSocket连接建立以后,其实只是简单规定了一下:接下来,咱们通信就不使用HTTP协议了,直接互相发数据吧。

安全的WebSocket连接机制和HTTPS类似。首先,浏览器用wss://xxx创建WebSocket连接时,会先通过HTTPS创建安全的连接,然后,该HTTPS连接升级为WebSocket连接,底层通信走的仍然是安全的SSL/TLS协议。

 

JAVA实现多人同时聊天

后台代码

package websocket; import org.json.JSONArray; import org.json.JSONObject; import javax.websocket.*; import javax.websocket.server.ServerEndpoint; import java.io.IOException; import java.util.HashMap; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; @ServerEndpoint("/chat") public class WebSocketServer { private static int onlineCount = 0; //记录连接人数 //通过key值去找寻对应的session private static Map clients = new ConcurrentHashMap(); private Session session;//记录登录人的session /** * 打开连接,保存连接的用户 * @param session * @throws IOException */ @OnOpen public void onOpen(Session session) throws IOException { this.session = session; this.userId = "user"+this.onlineCount;//由于用连接数去区分不同的连接人 addOnlineCount(); clients.put(userId, this); } /** * 关闭连接,删除用户 * @throws IOException */ @OnClose public void onClose() throws IOException { clients.remove(this.userId); subOnlineCount(); } /** * 发送消息 * @param message * @throws IOException */ @OnMessage public void onMessage(String message) throws IOException { sendMessageAll(userId+":"+message); } /** * 错误打印 * @param session * @param error */ @OnError public void onError(Session session, Throwable error) { error.printStackTrace(); } /** * 通过session群聊发送消息 * @param message * @throws IOException */ public void sendMessageAll(String message) throws IOException { for (WebSocketServer item : clients.values()) { item.session.getAsyncRemote().sendText(message); } } /** * 获取当前在线人数,线程安全 * @return */ public static synchronized int getOnlineCount() { return onlineCount; } /** * 添加当前在线人数 */ public static synchronized void addOnlineCount() { WebSocketServer.onlineCount++; WebSocketServer.id++; } /** * 减少当前在线人数 */ public static synchronized void subOnlineCount() { WebSocketServer.onlineCount--; } /** * * @return */ public static synchronized Map getClients() { return clients; } }

前台代码

WebSocket Demo html, body{ margin: 0; padding: 0; } header{ width: 100%; height: 100px; text-align: center; font-size: 50px; line-height: 100px; font-family: "微软雅黑"; border-bottom: 1px solid black; margin-bottom: 10px; } #messages{ padding: 10px; font-size: 20px;} WebSocket var webSocket = null; $(function(){ if('WebSocket' in window){ startConnect(); }else{ alert('你的浏览器不支持WebSocket'); } }); function startConnect(){ //记住 是ws开关 是ws开关 是ws开关 ws://IP:端口/项目名/Server.java中的@ServerEndpoint的value webSocket = new WebSocket("ws://localhost:8080/WebSocketTest_war_exploded/chat");//一个websocket webSocket.onerror = function(event) {//websocket的连接失败后执行的方法 onError(event); }; webSocket.onopen = function(event) {//websocket的连接成功后执行的方法 onOpen(event) }; webSocket.onmessage = function(event) {//websocket的接收消息时执行的方法 onMessage(event) }; } function colseConnect(){//关闭连接 webSocket.close(); } function onMessage(event) { $("#allMsg").append("

" + event.data + "

"); } function onOpen(event) { console.log("成功连接服务器"); $("#allMsg").append("

已连接至服务器

"); } function onError(event) { console.log("连接服务器失败"); $("#allMsg").append("

连接服务器发生错误

"); } function sendMessage(){ webSocket.send($("#msg").val());//向服务器发送消息 $("#msg").val("");//清空输入框 } ;

但是由于WebSocket不是完整的HTTP协议,所以不能在创建连接是通过request去传递参数。

以下有四种传递参数的方法:

1、url站位,通过@PathParam注释获取 

websocket的url :“ws://localhost:8080/WebSocketTest_war_exploded/chat/111”

socket的注解:“@ServerEndpoint("/chat/{userId}")”

方法中接收参数:

@OnOpen public void onOpen(Session session, @PathParam("userId") String userId)

2、url站位,通过session.getPathParameters()获取 

通过url的站位去传递参数,由于是记录session,所以可以通过session去获取站位的参数

3、url传参,通过session.getQueryString() 

4、url传参,通过session.getRequestURI().toString()

websocket的url:“ws://localhost:8080/WebSocketTest_war_exploded/chat?userId=111”

后台session.getQueryString()获取到userId=111

session.getRequestURI().toString()获取的是/chat?userId=111

 

从结果可以看出1、2两个方法不需要截取,可以直接使用;而3、4两个方法都需要截取字符串,稍微麻烦,但是请求的url比较清爽。

 

以上就是webSocket实现多人聊天的内容了。

 

实现私聊功能

后台代码

package com.zwb.websocket; import com.alibaba.fastjson.JSONObject; import com.zwb.pojo.User; import com.alibaba.fastjson.JSON; import javax.websocket.*; import javax.websocket.server.PathParam; import javax.websocket.server.ServerEndpoint; import java.io.IOException; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; @ServerEndpoint("/chat/{userId}") public class WebSocketServer { private static int onlineCount = 0; private static Map clients = new ConcurrentHashMap(); private Session session; private String userId; private static int id = 0; /** * 打开连接,保存连接的用户 * @param session * @param userId * @throws IOException */ @OnOpen public void onOpen(Session session, @PathParam("userId") String userId) throws IOException { this.session = session; this.userId = userId; addOnlineCount(); clients.put(userId, this); } /** * 关闭连接,删除用户 * @throws IOException */ @OnClose public void onClose() throws IOException { clients.remove(this.userId); subOnlineCount(); } /** * 发送消息 * @param message * @throws IOException */ @OnMessage public void onMessage(String message) throws IOException { //解析json字符串 Map map = jsonToMap(message); String sendUid = (String) map.get("sendUid"); String getUid = (String) map.get("getUid"); String messageContent = (String) map.get("messageContent"); if(getUid.equals("ALL")){ sendMessageAll(messageContent); }else{ sendMessageTo(messageContent, sendUid, getUid); } } /** * 错误打印 * @param session * @param error */ @OnError public void onError(Session session, Throwable error) { error.printStackTrace(); } /** * 消息发送 * @param message * @param getUid * @throws IOException */ public void sendMessageTo(String message,String sendUid, String getUid) throws IOException { WebSocketServer item = clients.get(getUid); if(item != null) { Map map = new HashMap(); //消息内容包括发送者,接受者和消息内容 map.put("sendUser", sendUid); map.put("message", message); map.put("getUser", getUid); JSONObject jsonObject = new JSONObject(map); item.session.getAsyncRemote().sendText(jsonObject.toString()); }else{//离线消息发送 } } /** * 群聊发送消息 * @param message * @throws IOException */ public void sendMessageAll(String message) throws IOException { for (WebSocketServer item : clients.values()) { item.session.getAsyncRemote().sendText(message); } } /** * 获取当前在线人数,线程安全 * @return */ public static synchronized int getOnlineCount() { return onlineCount; } /** * 添加当前在线人数 */ public static synchronized void addOnlineCount() { WebSocketServer.onlineCount++; } /** * 减少当前在线人数 */ public static synchronized void subOnlineCount() { WebSocketServer.onlineCount--; } /** * * @return */ public static synchronized Map getClients() { return clients; } //解析json数据 public Map jsonToMap(String jsonStr){ Map map = JSON.parseObject(jsonStr); return map; } public List jsonToList(String jsonStr){ List list = JSON.parseArray(jsonStr); return list; } }

私聊功能其实和多人同时聊天区别不大

由于是通过session冲服务端向客户端传输数据,所以在客户端进行websocket连接时向后台传输与session对应的id,以上述代码为例,就是登陆人的userId。

然后在发送信息的时候传递发送人的userId,接收人的userId以及发送的信息。

这个时候就可以通过记录所有登陆人userId和session的clients去搜索出对应接收人的session,然后编写信息。



【本文地址】


今日新闻


推荐新闻


CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3