• 使用webSocket Springboot vue实现客户端与服务端通


    WebSocket是什么?

    WebSocket 是 HTML5 开始提供的一种在单个 TCP 连接上进行全双工通讯的协议。

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

    在 WebSocket API 中,浏览器和服务器只需要做一个握手的动作,然后,浏览器和服务器之间就形成了一条快速通道。两者之间就直接可以数据互相传送。

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

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

    浏览器通过 JavaScript 向服务器发出建立 WebSocket 连接的请求,连接建立以后,客户端和服务器端就可以通过 TCP 连接直接交换数据。

    当你获取 Web Socket 连接后,你可以通过 send() 方法来向服务器发送数据,并通过 onmessage 事件来接收服务器返回的数据。

    创建WebSocket 对象

    var Socket = new WebSocket(url, [protocol] );

    以上代码中的第一个参数 url, 指定连接的 URL。第二个参数 protocol 是可选的,指定了可接受的子协议。

    WebSocket实现

    WebSocket 协议本质上是一个基于 TCP 的协议。

    为了建立一个 WebSocket 连接,客户端浏览器首先要向服务器发起一个 HTTP 请求,这个请求和通常的 HTTP 请求不同,包含了一些附加头信息,其中附加头信息"Upgrade: WebSocket"表明这是一个申请协议升级的 HTTP 请求,服务器端解析这些附加的头信息然后产生应答信息返回给客户端,客户端和服务器端的 WebSocket 连接就建立起来了,双方就可以通过这个连接通道自由的传递信息,并且这个连接会持续存在直到客户端或者服务器端的某一方主动的关闭连接。

    WebSocket 事件

    以下是 WebSocket 对象的相关事件。假定我们使用了以上代码创建了 Socket 对象:

    事件事件处理程序描述
    openSocket.onopen连接建立时触发
    messageSocket.onmessage客户端接收服务端数据时触发
    errorSocket.onerror通信发生错误时触发
    closeSocket.onclose连接关闭时触发

    WebSocket 方法

    以下是 WebSocket 对象的相关方法。假定我们使用了以上代码创建了 Socket 对象:

    方法描述
    Socket.send()

    使用连接发送数据

    Socket.close()

    关闭连接

     

    聊天室效果呈现

     

    学习博客:Springboot+Vue实现在线聊天(通用版)_程序员青戈的博客-CSDN博客_springboot聊天

    1.SpringBoot引入Websocket依赖

    1. org.springframework.boot
    2. spring-boot-starter-websocket

    2.创建配置类

    1. import org.springframework.context.annotation.Bean;
    2. import org.springframework.context.annotation.Configuration;
    3. import org.springframework.web.socket.server.standard.ServerEndpointExporter;
    4. /**
    5. * 开启WebSocket服务端的自动注册
    6. */
    7. @Configuration
    8. public class WebSocketConfig {
    9. @Bean
    10. public ServerEndpointExporter serverEndpointExporter() {
    11. return new ServerEndpointExporter();
    12. }
    13. }

    3.创建一个WebSocketServer来处理通信(我在这里设置了一个用户集合,和客服集合来分别保存用户和客户,客服传过来的status='1',用户传过来的status='0')

    1. package com.example.go.controller.webSocket;
    2. import cn.hutool.json.JSONArray;
    3. import cn.hutool.json.JSONObject;
    4. import cn.hutool.json.JSONUtil;
    5. import com.example.go.entity.ChatPeople;
    6. import org.slf4j.Logger;
    7. import org.slf4j.LoggerFactory;
    8. import org.springframework.stereotype.Component;
    9. import javax.websocket.*;
    10. import javax.websocket.server.PathParam;
    11. import javax.websocket.server.ServerEndpoint;
    12. import java.text.ParseException;
    13. import java.util.Map;
    14. import java.util.concurrent.ConcurrentHashMap;
    15. /**
    16. * @author websocket服务
    17. */
    18. @ServerEndpoint(value = "/imserver/{username}/{id}/{status}")
    19. @Component
    20. public class WebSocketServer {
    21. private static final Logger log = LoggerFactory.getLogger(WebSocketServer.class);
    22. /**
    23. * 记录当前在线连接数
    24. */
    25. public static final Map sessionMap = new ConcurrentHashMap<>();
    26. //用户集合
    27. public static final Map userMap = new ConcurrentHashMap<>();
    28. //客服集合
    29. public static final Map managerMap = new ConcurrentHashMap<>();
    30. /**
    31. * 连接建立成功调用的方法
    32. */
    33. @OnOpen
    34. public void onOpen(Session session, @PathParam("username") String username,@PathParam("id") Integer id,@PathParam("status") String status) {
    35. ChatPeople chatPeople = new ChatPeople(id,username,status);
    36. System.out.println(chatPeople);
    37. System.out.println(session);
    38. sessionMap.put(chatPeople, session);
    39. if ( status.equals("1") ){//客服
    40. managerMap.put(username,chatPeople);
    41. } else {//用户
    42. userMap.put(username,chatPeople);
    43. }
    44. log.info("有新用户加入,username={}, 当前在线人数为:{}", username, sessionMap.size());
    45. JSONObject result = new JSONObject();
    46. JSONArray array = new JSONArray();
    47. result.set("users", array);
    48. for (Object key : sessionMap.keySet()) {
    49. JSONObject jsonObject = new JSONObject();
    50. jsonObject.set("user", key);
    51. // {"user":{"id":6,"username":"11","status":"2"}}
    52. array.add(jsonObject);
    53. }
    54. // {"users":[{"user":{"id":6,"username":"11","status":"2"}}]}
    55. sendAllMessage(JSONUtil.toJsonStr(result)); // 后台发送消息给所有的客户端
    56. }
    57. /**
    58. * 连接关闭调用的方法
    59. */
    60. @OnClose
    61. public void onClose(Session session, @PathParam("username") String username,@PathParam("id") Integer id,@PathParam("status") String status) {
    62. ChatPeople chatPeople = new ChatPeople(id,username,status);
    63. sessionMap.remove(chatPeople);
    64. log.info("有一连接关闭,移除username={}的用户session, 当前在线人数为:{}", username, sessionMap.size());
    65. }
    66. /**
    67. * 收到客户端消息后调用的方法
    68. * 后台收到客户端发送过来的消息
    69. * onMessage 是一个消息的中转站
    70. * 接受 浏览器端 socket.send 发送过来的 json数据
    71. * @param message 客户端发送过来的消息
    72. */
    73. @OnMessage
    74. public void onMessage(String message, Session session, @PathParam("username") String username,@PathParam("id") Integer id,@PathParam("status") String status) throws ParseException {
    75. log.info("服务端收到用户username={}的消息:{}", username, message);
    76. JSONObject obj = JSONUtil.parseObj(message);
    77. String toUsername = obj.getStr("to"); // to表示发送给哪个用户,比如 admin
    78. String text = obj.getStr("text"); // 发送的消息文本 hello
    79. //创建聊天对象
    80. ChatPeople chatPeople;
    81. if ( status.equals("2") ){//客服
    82. chatPeople = managerMap.get(toUsername);
    83. }else{//用户
    84. chatPeople = userMap.get(toUsername);
    85. }
    86. System.out.println("要发送消息的对象:"+chatPeople);
    87. Session toSession = sessionMap.get(chatPeople); // 根据 to用户名来获取 session,再通过session发送消息文本
    88. System.out.println(toSession);
    89. if (toSession != null) {
    90. // 服务器端 再把消息组装一下,组装后的消息包含发送人和发送的文本内容
    91. // {"from": "zhang", "text": "hello"}
    92. JSONObject jsonObject = new JSONObject();
    93. jsonObject.set("from", username); // from 是 zhang
    94. jsonObject.set("text", text); // text 同上面的text
    95. this.sendMessage(jsonObject.toString(), toSession);
    96. log.info("发送给用户username={},消息:{}", toUsername, jsonObject.toString());
    97. } else {
    98. log.info("发送失败,未找到用户username={}的session", toUsername);
    99. }
    100. }
    101. @OnError
    102. public void onError(Session session, Throwable error) {
    103. log.error("发生错误");
    104. error.printStackTrace();
    105. }
    106. /**
    107. * 服务端发送消息给客户端
    108. */
    109. private void sendMessage(String message, Session toSession) {
    110. try {
    111. log.info("服务端给客户端[{}]发送消息{}", toSession.getId(), message);
    112. toSession.getBasicRemote().sendText(message);
    113. } catch (Exception e) {
    114. log.error("服务端发送消息给客户端失败", e);
    115. }
    116. }
    117. /**
    118. * 服务端发送消息给所有客户端
    119. */
    120. private void sendAllMessage(String message) {
    121. try {
    122. for (Session session : sessionMap.values()) {
    123. log.info("服务端给客户端[{}]发送消息{}", session.getId(), message);
    124. session.getBasicRemote().sendText(message);
    125. }
    126. } catch (Exception e) {
    127. log.error("服务端发送消息给客户端失败", e);
    128. }
    129. }
    130. }

    4.前端代码

    1. <template>
    2. <div style="padding: 10px; margin-bottom: 50px">
    3. <el-row>
    4. <el-col :span="4">
    5. <el-card style="width: 300px; height: 300px; color: #333">
    6. <div style="padding-bottom: 10px; border-bottom: 1px solid #ccc">
    7. 在线用户<span style="font-size: 12px"
    8. >(点击聊天气泡开始聊天)
    9. >
    10. div>
    11. <div
    12. style="padding: 10px 0"
    13. v-for="user in users"
    14. :key="user.user.username"
    15. >
    16. <span>{{ user.user.username }}span>
    17. <i
    18. class="el-icon-chat-dot-round"
    19. style="margin-left: 10px; font-size: 16px; cursor: pointer"
    20. @click="chatUser = user.user.username"
    21. >i>
    22. <span
    23. style="font-size: 12px; color: limegreen; margin-left: 5px"
    24. v-if="user.user.username === chatUser"
    25. >chatting...
    26. >
    27. div>
    28. el-card>
    29. el-col>
    30. <el-col :span="20">
    31. <div style="
    32. width: 800px;
    33. margin: 0 auto;
    34. background-color: white;
    35. border-radius: 5px;
    36. box-shadow: 0 0 10px #ccc;
    37. "
    38. >
    39. <div style="text-align: center; line-height: 50px">
    40. Web聊天室({{ chatUser }})
    41. div>
    42. <div
    43. style="height: 350px; overflow: auto; border-top: 1px solid #ccc"
    44. v-html="content"
    45. >div>
    46. <div class="chat">
    47. <div style="height: 200px">
    48. <textarea
    49. v-model="text"
    50. style="
    51. height: 160px;
    52. width: 95%;
    53. padding: 20px;
    54. border: none;
    55. border-top: 1px solid #ccc;
    56. border-bottom: 1px solid #ccc;
    57. outline: none;
    58. "
    59. >textarea>
    60. <div style="text-align: right; padding-right: 10px">
    61. <el-button type="primary" size="mini" @click="send"
    62. >发送
    63. >
    64. div>
    65. div>
    66. div>
    67. div>
    68. el-col>
    69. el-row>
    70. div>
    71. template>
    72. <script>
    73. let socket;
    74. export default {
    75. name: "Im",
    76. data() {
    77. return {
    78. circleUrl:
    79. "https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png",
    80. user: {},
    81. isCollapse: false,
    82. users: [],
    83. chatUser: "",
    84. text: "",
    85. messages: [],
    86. content: "",
    87. };
    88. },
    89. created() {
    90. this.init();
    91. },
    92. methods: {
    93. send() {
    94. if (!this.chatUser) {
    95. this.$message({ type: "warning", message: "请选择聊天对象" });
    96. return;
    97. }
    98. if (!this.text) {
    99. this.$message({ type: "warning", message: "请输入内容" });
    100. } else {
    101. if (typeof WebSocket == "undefined") {
    102. console.log("您的浏览器不支持WebSocket");
    103. } else {
    104. console.log("您的浏览器支持WebSocket");
    105. // 组装待发送的消息 json
    106. // {"from": "zhang", "to": "admin", "text": "聊天文本"}
    107. let message = {
    108. from: this.user.username,
    109. to: this.chatUser,
    110. text: this.text,
    111. };
    112. socket.send(JSON.stringify(message)); // 将组装好的json发送给服务端,由服务端进行转发
    113. this.messages.push({ user: this.user.username, text: this.text });
    114. // 构建消息内容,本人消息
    115. this.createContent(null, this.user.username, this.text);
    116. this.text = "";
    117. }
    118. }
    119. },
    120. createContent(remoteUser, nowUser, text) {
    121. // 这个方法是用来将 json的聊天消息数据转换成 html的。
    122. let html;
    123. // 当前用户消息
    124. if (nowUser) {
    125. // nowUser 表示是否显示当前用户发送的聊天消息,绿色气泡
    126. html =
    127. '
      \n' +
    128. '
      \n' +
    129. '
      ' +
    130. text +
    131. "
      \n" +
  • "
    \n" +
  • '
    \n' +
  • ' \n' +
  • ' \n' +
  • " \n" +
  • "
    \n" +
  • "
    ";
  • } else if (remoteUser) {
  • // remoteUser表示远程用户聊天消息,蓝色的气泡
  • html =
  • '
    \n' +
  • '
    \n' +
  • ' \n' +
  • ' \n' +
  • " \n" +
  • "
    \n" +
  • '
    \n' +
  • '
    ' +
  • text +
  • "
    \n" +
  • "
    \n" +
  • "
    ";
  • }
  • console.log(html);
  • this.content += html;
  • },
  • init() {
  • this.user = JSON.parse(localStorage.getItem("user"));
  • let username = this.user.username;
  • let id = this.user.id;
  • let _this = this;
  • if (typeof WebSocket == "undefined") {
  • console.log("您的浏览器不支持WebSocket");
  • } else {
  • console.log("您的浏览器支持WebSocket");
  • let socketUrl =
  • "ws://localhost:8088/imserver/" + username + "/" + id + "/" + 1;
  • if (socket != null) {
  • socket.close();
  • socket = null;
  • }
  • // 开启一个websocket服务
  • socket = new WebSocket(socketUrl);
  • //打开事件
  • socket.onopen = function () {
  • console.log("websocket已打开");
  • };
  • // 浏览器端收消息,获得从服务端发送过来的文本消息
  • socket.onmessage = function (msg) {
  • console.log("收到数据====" + msg.data);
  • const data = JSON.parse(msg.data); // 对收到的json数据进行解析, 类似这样的: {"users":[{"user":{"id":11,"username":"6","status":"2"}}]}
  • if (data.users) {
  • console.log(data.users, "users");
  • // 获取在线人员信息
  • _this.users = data.users.filter(
  • (user) =>
  • user.user.username !== username &&
  • user.user.id !== id &&
  • user.user.status !== "1"
  • ); // 获取当前连接的所有用户信息,并且排除自身,自己不会出现在自己的聊天列表里
  • } else {
  • // 如果服务器端发送过来的json数据 不包含 users 这个key,那么发送过来的就是聊天文本json数据
  • // {"from": "zhang", "text": "hello"}
  • if (data.from === _this.chatUser) {
  • _this.messages.push(data);
  • // 构建消息内容
  • _this.createContent(data.from, null, data.text);
  • }
  • }
  • };
  • //关闭事件
  • socket.onclose = function () {
  • console.log("websocket已关闭");
  • };
  • //发生了错误事件
  • socket.onerror = function () {
  • console.log("websocket发生了错误");
  • };
  • }
  • },
  • },
  • };
  • script>
  • <style>
  • .tip {
  • color: white;
  • text-align: left;
  • border-radius: 10px;
  • font-family: sans-serif;
  • padding: 10px;
  • max-width: 400px;
  • word-break: break-all;
  • display: inline-block !important;
  • display: inline;
  • }
  • .right {
  • background-color: deepskyblue;
  • }
  • .left {
  • background-color: forestgreen;
  • }
  • style>
  • (这里是传过去的是客服,如果要修改成用户的话)

    改成'2'就行了

    还要注意的一个点就是

      this.user = JSON.parse(localStorage.getItem("user"));

     在保存user时一个使用JSON.stringify

    ocalStorage.setItem("user",JSON.stringify(message.data.manager))

    在测试的时候,要用两个不同的游览器测试。

  • 相关阅读:
    940. 不同的子序列 II
    时序数据库 TimescaleDB 基础概念
    【C语言】循环语句详解
    (c++)类和对象中篇
    CSDN获评2022年科创中国开源创新榜「开源机构」
    8.cmake常用命令
    vue监听表单输入的身份证号自动填充性别和生日
    Koa 源码剖析
    graphviz 绘制红黑树
    RabbitMQ 消息中间件 消息队列
  • 原文地址:https://blog.csdn.net/bu_xiang_tutou/article/details/128178053