赞
踩
WebSocket 是 HTML5 开始提供的一种在单个 TCP 连接上进行全双工通讯的协议。
WebSocket 使得客户端和服务器之间的数据交换变得更加简单,允许服务端主动向客户端推送数据。在 WebSocket API 中,浏览器和服务器只需要完成一次握手,两者之间就直接可以创建持久性的连接,并进行双向数据传输。
在 WebSocket API 中,浏览器和服务器只需要做一个握手的动作,然后,浏览器和服务器之间就形成了一条快速通道。两者之间就直接可以数据互相传送。
现在,很多网站为了实现推送技术,所用的技术都是 Ajax 轮询。轮询是在特定的的时间间隔(如每1秒),由浏览器对服务器发出HTTP请求,然后由服务器返回最新的数据给客户端的浏览器。这种传统的模式带来很明显的缺点,即浏览器需要不断的向服务器发出请求,然而HTTP请求可能包含较长的头部,其中真正有效的数据可能只是很小的一部分,显然这样会浪费很多的带宽等资源。
HTML5 定义的 WebSocket 协议,能更好的节省服务器资源和带宽,并且能够更实时地进行通讯。
最近在做类似于电商网站的项目,其中需要用到消息推送、在线聊天的功能,本程序讲解怎么实现利用两个客户端完成在线聊天的功能,适用场景可以用于“客服聊天、多人群聊、消息推送”等。利用Vue做了一个比较简易的聊天界面,如下所示:
1.引入此次项目的目的依赖包
- <!--websocket依赖-->
- <dependency>
- <groupId>org.springframework.boot</groupId>
- <artifactId>spring-boot-starter-websocket</artifactId>
- </dependency>
- <!-- Gson依赖 -->
- <dependency>
- <groupId>com.squareup.retrofit2</groupId>
- <artifactId>converter-gson</artifactId>
- <version>2.6.2</version>
- </dependency>
注:WebSocket依赖是所必须的,毕竟要站在巨人的肩膀上进行开发,但其实也可以写成原生的,不需要依靠任何依赖,直接自己写底层,而Gson就不必多做介绍了,我这里主要是想将发送给前端的有效数据转成以json的形式。
2.编写WebSocket的配置类
- package com.chen.config;
-
- import org.springframework.context.annotation.Bean;
- import org.springframework.context.annotation.Configuration;
- import org.springframework.web.socket.server.standard.ServerEndpointExporter;
-
- /**
- * @author chen
- * @date 2019/10/26
- * @email 15218979950@163.com
- * @description WebSocketConfig配置类,注入对象ServerEndpointExporter,
- * * 这个bean会自动注册使用了@ServerEndpoint注解声明的Websocket endpoint
- */
- @Configuration
- public class WebSocketConfig {
- @Bean
- public ServerEndpointExporter serverEndpointExporter() {
- return new ServerEndpointExporter();
- }
- }

3.封装消息实体
- package com.chen.entity;
-
- /**
- * @author chen
- * @date 2019/10/26
- * @email 15218979950@163.com
- * @description 消息实体
- */
- public class SocketMsg {
- private int type; //聊天类型0:群聊,1:单聊.
- private String fromUser;//发送者.
- private String toUser;//接受者.
- private String msg;//消息
-
- public int getType() {
- return type;
- }
-
- public void setType(int type) {
- this.type = type;
- }
-
- public String getFromUser() {
- return fromUser;
- }
-
- public void setFromUser(String fromUser) {
- this.fromUser = fromUser;
- }
-
- public String getToUser() {
- return toUser;
- }
-
- public void setToUser(String toUser) {
- this.toUser = toUser;
- }
-
- public String getMsg() {
- return msg;
- }
-
- public void setMsg(String msg) {
- this.msg = msg;
- }
-
- }

4.WebSocket实现类
- package com.chen.service;
-
- import com.chen.entity.SocketMsg;
- import com.fasterxml.jackson.core.JsonParseException;
- import com.fasterxml.jackson.databind.JsonMappingException;
- import com.fasterxml.jackson.databind.ObjectMapper;
- import com.google.gson.Gson;
- import org.springframework.stereotype.Component;
-
- import javax.websocket.*;
- import javax.websocket.server.PathParam;
- import javax.websocket.server.ServerEndpoint;
- import java.io.IOException;
- import java.util.HashMap;
- import java.util.Map;
- import java.util.concurrent.CopyOnWriteArraySet;
-
- /**
- * @author chen
- * @date 2019/10/26
- * @email 15218979950@163.com
- * @description websocket的具体实现类
- * 使用springboot的唯一区别是要@Component声明,而使用独立容器是由容器自己管理websocket的,
- * 但在springboot中连容器都是spring管理的。
- * 虽然@Component默认是单例模式的,但springboot还是会为每个websocket连接初始化一个bean,
- * 所以可以用一个静态set保存起来
- */
- @ServerEndpoint(value = "/websocket/{nickname}")
- @Component
- public class WebSocketService {
- private String nickname;
- private Session session;
-
- //用来存放每个客户端对应的MyWebSocket对象。
- private static CopyOnWriteArraySet<WebSocketService> webSocketSet = new CopyOnWriteArraySet<WebSocketService>();
- //与某个客户端的连接会话,需要通过它来给客户端发送数据
- //用来记录sessionId和该session进行绑定
- private static Map<String, Session> map = new HashMap<String, Session>();
-
- /**
- * 连接建立成功调用的方法
- */
- @OnOpen
- public void onOpen(Session session, @PathParam("nickname") String nickname) {
- Map<String,Object> message=new HashMap<String, Object>();
- this.session = session;
- this.nickname = nickname;
- map.put(session.getId(), session);
- webSocketSet.add(this);//加入set中
- System.out.println("有新连接加入:" + nickname + ",当前在线人数为" + webSocketSet.size());
- //this.session.getAsyncRemote().sendText("恭喜" + nickname + "成功连接上WebSocket(其频道号:" + session.getId() + ")-->当前在线人数为:" + webSocketSet.size());
- message.put("type",0); //消息类型,0-连接成功,1-用户消息
- message.put("people",webSocketSet.size()); //在线人数
- message.put("name",nickname); //昵称
- message.put("aisle",session.getId()); //频道号
- this.session.getAsyncRemote().sendText(new Gson().toJson(message));
- }
-
- /**
- * 连接关闭调用的方法
- */
- @OnClose
- public void onClose() {
- webSocketSet.remove(this); //从set中删除
- System.out.println("有一连接关闭!当前在线人数为" + webSocketSet.size());
- }
-
- /**
- * 收到客户端消息后调用的方法
- * @param message 客户端发送过来的消息
- */
- @OnMessage
- public void onMessage(String message, Session session, @PathParam("nickname") String nickname) {
- System.out.println("来自客户端的消息-->" + nickname + ": " + message);
-
- //从客户端传过来的数据是json数据,所以这里使用jackson进行转换为SocketMsg对象,
- // 然后通过socketMsg的type进行判断是单聊还是群聊,进行相应的处理:
- ObjectMapper objectMapper = new ObjectMapper();
- SocketMsg socketMsg;
-
- try {
- socketMsg = objectMapper.readValue(message, SocketMsg.class);
- if (socketMsg.getType() == 1) {
- //单聊.需要找到发送者和接受者.
- socketMsg.setFromUser(session.getId());//发送者.
- Session fromSession = map.get(socketMsg.getFromUser());
- Session toSession = map.get(socketMsg.getToUser());
- //发送给接受者.
- if (toSession != null) {
- //发送给发送者.
- Map<String,Object> m=new HashMap<String, Object>();
- m.put("type",1);
- m.put("name",nickname);
- m.put("msg",socketMsg.getMsg());
- fromSession.getAsyncRemote().sendText(new Gson().toJson(m));
- toSession.getAsyncRemote().sendText(new Gson().toJson(m));
- } else {
- //发送给发送者.
- fromSession.getAsyncRemote().sendText("系统消息:对方不在线或者您输入的频道号不对");
- }
- } else {
- //群发消息
- broadcast(nickname + ": " + socketMsg.getMsg());
- }
-
- } catch (JsonParseException e) {
- e.printStackTrace();
- } catch (JsonMappingException e) {
- e.printStackTrace();
- } catch (IOException e) {
- e.printStackTrace();
- }
- }
-
- /**
- * 发生错误时调用
- */
- @OnError
- public void onError(Session session, Throwable error) {
- System.out.println("发生错误");
- error.printStackTrace();
- }
-
- /**
- * 群发自定义消息
- */
- public void broadcast(String message) {
- for (WebSocketService item : webSocketSet) {
- item.session.getAsyncRemote().sendText(message);//异步发送消息.
- }
- }
- }

这里为了方便开发,合理地显示出效果,我使用了Element-ui框架。
- <template>
- <div>
- <el-row :gutter="20">
- <el-col :span="12" :offset="6">
- <div class="main">
- <el-row>
- <el-input
- placeholder="请输入自己的昵称"
- prefix-icon="el-icon-user-solid"
- v-model="name"
- style="width:50%"
- ></el-input>
- <el-button type="primary" @click="conectWebSocket()">建立连接</el-button>
- <el-button type="danger">断开连接</el-button>
- </el-row>
- <el-row>
- <el-input
- placeholder="请输入对方频道号"
- prefix-icon="el-icon-phone"
- v-model="aisle"
- style="width:40%"
- ></el-input>
- </el-row>
- <el-row>
- <el-input
- placeholder="请输入要发送的消息"
- prefix-icon="el-icon-s-promotion"
- v-model="messageValue"
- style="width:50%"
- ></el-input>
- <el-button type="primary" @click="sendMessage()">发送</el-button>
- </el-row>
- <div class="message">
- <div v-for="(value,key,index) in messageList" :key="index">
- <el-tag v-if="value.name==name" type="success" style="float:right">我:{{value.msg}}</el-tag>
- <br />
- <el-tag v-if="value.name!=name" style="float:left">{{value.name}}:{{value.msg}}</el-tag>
- <br />
- </div>
- </div>
- </div>
- </el-col>
- </el-row>
- </div>
- </template>
-
- <script>
- export default {
- data() {
- return {
- name: "", // 昵称
- websocket: null, // WebSocket对象
- aisle: "", // 对方频道号
- messageList: [], // 消息列表
- messageValue: "" // 消息内容
- };
- },
- methods: {
- conectWebSocket: function() {
- console.log("建立连接");
- if (this.name === "") {
- this.$alert("请输入自己的昵称", "提示", {
- confirmButtonText: "确定",
- callback: action => {}
- });
- } else {
- //判断当前浏览器是否支持WebSocket
- if ("WebSocket" in window) {
- this.websocket = new WebSocket(
- "ws://localhost:8080/websocket/" + this.name
- );
- } else {
- alert("不支持建立socket连接");
- }
- //连接发生错误的回调方法
- this.websocket.onerror = function() {
-
- };
- //连接成功建立的回调方法
- this.websocket.onopen = function(event) {
-
- };
- //接收到消息的回调方法
- var that = this;
- this.websocket.onmessage = function(event) {
- var object = eval("(" + event.data + ")");
- console.log(object);
- if (object.type == 0) {
- // 提示连接成功
- console.log("连接成功");
- that.showInfo(object.people, object.aisle);
- }
- if (object.type == 1) {
- //显示消息
- console.log("接受消息");
- that.messageList.push(object);
- }
- };
- //连接关闭的回调方法
- this.websocket.onclose = function() {};
- //监听窗口关闭事件,当窗口关闭时,主动去关闭websocket连接,防止连接还没断开就关闭窗口,server端会抛异常。
- window.onbeforeunload = function() {
- this.websocket.close();
- };
- }
- },
- // 发送消息
- sendMessage: function() {
- var socketMsg = { msg: this.messageValue, toUser: this.aisle };
- if (this.aisle == "") {
- //群聊.
- socketMsg.type = 0;
- } else {
- //单聊.
- socketMsg.type = 1;
- }
- this.websocket.send(JSON.stringify(socketMsg));
- },
- showInfo: function(people, aisle) {
- this.$notify({
- title: "当前在线人数:" + people,
- message: "您的频道号:" + aisle,
- duration: 0
- });
- }
- }
- };
- </script>
-
- <style scoped>
- .main {
- position: relative;
- top: 20px;
- }
- .message {
- position: relative;
- overflow:auto;
- top: 20px;
- width: 100%;
- height: 40%;
- box-shadow: 0 2px 4px rgba(0, 0, 0, 0.12), 0 0 6px rgba(0, 0, 0, 0.04);
- padding: 5px;
- }
- </style>

Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。