当前位置:   article > 正文

WebSocket 快速实操 这篇就够了_js websocket 发送json数据

js websocket 发送json数据

目录

目录

1.WebSocket概述

2.引入依赖

3.config

4.发送单条数据的server和html

4.1server

4.2html

5.发送Json类型数据的server和html

5.1server

5.2html

6.对于WebSocketServer的中无法直接使用@Autowired注解获取对象的方法和使用方式


1.WebSocket概述

        WebSocket是HTML5开始提供的一种在单个TCP连接上进行全双工通讯的协议。它允许服务端主动发送信息给客户端,是实现推送(Push)技术的一种非常流行的解决方案。

WebSocket的特点:
(1)全双工通信:与传统的HTTP请求-响应不同,WebSocket支持服务器和客户端之间的全双工通信。
(2)单连接:WebSocket连接一旦建立,就可以送和接收无数个消息。
(3)服务器主动推送:服务器可以主动发送信息给客户端,不需要客户端不断地询问服务器是否有新信息。
(4)持久连接:与传统的基于轮询(Polling)的推送技术相比,WebSocket连接一旦建立,就可以持续开放,减少了因频繁建立和关闭连接而造成的开销。
(5)协议升级:WebSocket协议通过握手过程从HTTP协议升级而来,其初始的握手请求是一个升级请求。

2.引入依赖

  1. <dependency>
  2. <groupId>org.springframework.boot</groupId>
  3. <artifactId>spring-boot-starter-websocket</artifactId>
  4. </dependency>

3.config

  1. package com.example.springbootudp.config;
  2. import org.springframework.context.annotation.Bean;
  3. import org.springframework.context.annotation.Configuration;
  4. import org.springframework.web.socket.server.standard.ServerEndpointExporter;
  5. @Configuration
  6. public class WebSocketConfig {
  7. @Bean
  8. public ServerEndpointExporter serverEndpointExporter(){
  9. return new ServerEndpointExporter();
  10. }
  11. }

4.发送单条数据的server和html

4.1server

  1. package com.example.springbootudp.server;
  2. import jakarta.websocket.*;
  3. import jakarta.websocket.server.ServerEndpoint;
  4. import org.springframework.stereotype.Component;
  5. import org.springframework.web.socket.TextMessage;
  6. import java.io.IOException;
  7. @ServerEndpoint(value = "/chat")
  8. @Component
  9. public class WebSocketServer {
  10. @OnOpen
  11. public void onOpen(Session session, EndpointConfig config){
  12. }
  13. @OnMessage
  14. public void onMessage(String message,Session session) throws IOException {
  15. System.out.println(message);
  16. // 发送响应给客户端
  17. TextMessage response = new TextMessage("Server response: " + message);
  18. System.out.println("response.getPayload():"+response.getPayload());
  19. session.getBasicRemote().sendText(response.getPayload());
  20. }
  21. @OnClose
  22. public void onClose(Session session){
  23. }
  24. }

4.2html

  1. <!DOCTYPE html>
  2. <html>
  3. <head>
  4. <title>WebSocket Test</title>
  5. <script>
  6. const wsUri = "ws://localhost:8080/chat";
  7. const websocket = new WebSocket(wsUri);
  8. websocket.onopen = function() {
  9. console.log("WebSocket connection opened.");
  10. let message = document.getElementById('message').value;
  11. websocket.send(message);
  12. };
  13. websocket.onclose = function(evt) {
  14. console.log("WebSocket connection closed.");
  15. };
  16. websocket.onmessage = function(evt) {
  17. console.log("Received message:", event.data);
  18. // 可以在页面上显示接收到的消息
  19. var messages = document.getElementById('messages');
  20. var message = document.createElement('li');
  21. message.textContent = "Server: " + event.data;
  22. messages.appendChild(message);
  23. };
  24. websocket.onerror = function(evt) {
  25. console.log("WebSocket Error: " + evt.data);
  26. };
  27. // 修改后的 sendWebSocket 函数
  28. function sendWebSocketMessage() {
  29. // 确保在发送消息时连接已经打开
  30. if (websocket.readyState === WebSocket.OPEN) {
  31. let message = document.getElementById('message').value;
  32. websocket.send(message);
  33. } else {
  34. alert("WebSocket connection is not open.");
  35. }
  36. }
  37. </script>
  38. </head>
  39. <body>
  40. <ul id="messages"></ul>
  41. <input type="text" id="message" placeholder="请输入消息">
  42. <button onclick="sendWebSocketMessage()">发送消息</button>
  43. </body>
  44. </html>

5.发送Json类型数据的server和html

只需要将发送单条数据的server和html修改部分代码即可

5.1server

  1. @ServerEndpoint(value = "/chat")
  2. @Component
  3. public class WebSocketServer {
  4. // ... 其他代码 ...
  5. @OnMessage
  6. public void onMessage(String message, Session session) throws IOException {
  7. try {
  8. // 解析 JSON 字符串
  9. Object obj = JSON.parse(message);
  10. // 根据需要处理 obj,假设您需要处理的是一个带有 typecontent 的消息
  11. String type = (String) obj.get("type");
  12. String content = (String) obj.get("content");
  13. System.out.println("Received message: " + message);
  14. // 可能的响应处理
  15. if ("message".equals(type)) {
  16. // 处理消息内容
  17. System.out.println("Content: " + content);
  18. }
  19. // 发送响应给客户端
  20. TextMessage response = new TextMessage(JSON.stringify({"type": "response", "content": "Server response to JSON"}));
  21. session.getBasicRemote().sendText(response.getPayload());
  22. } catch (JSONException e) {
  23. e.printStackTrace();
  24. // 处理解析错误
  25. }
  26. }
  27. // ... 其他代码 ...
  28. }

5.2html

  1. <script>
  2. // ... 其他代码 ...
  3. function sendWebSocketMessage() {
  4. // 创建要发送的数据对象
  5. var messageObject = {
  6. type: "message",
  7. content: document.getElementById('message').value
  8. };
  9. // 将对象转换为 JSON 字符串
  10. var messageJSON = JSON.stringify(messageObject);
  11. // 确保在发送消息时连接已经打开
  12. if (websocket.readyState === WebSocket.OPEN) {
  13. websocket.send(messageJSON); // 发送 JSON 字符串
  14. } else {
  15. alert("WebSocket connection is not open.");
  16. }
  17. }
  18. // ... 其他代码 ...
  19. </script>

6.对于WebSocketServer的中无法直接使用@Autowired注解获取对象的方法和使用方式

  1. package com.example.springbootudp.server;
  2. import jakarta.websocket.*;
  3. import jakarta.websocket.server.ServerEndpoint;
  4. import org.springframework.stereotype.Component;
  5. import org.springframework.web.socket.TextMessage;
  6. import java.io.IOException;
  7. @ServerEndpoint(value = "/chat")
  8. @Component
  9. public class WebSocketServer {
  10. private static MessageService messageService;
  11. @Autowired
  12. public void setWebSocketServer(MessageService messageService){
  13. WebSocketServer.messageService =messageService;
  14. }
  15. @OnOpen
  16. public void onOpen(Session session, EndpointConfig config){
  17. }
  18. @OnMessage
  19. public void onMessage(String message,Session session) throws IOException {
  20. WebSocketServer.messageService.getById();
  21. }
  22. @OnClose
  23. public void onClose(Session session){
  24. }
  25. }

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/小惠珠哦/article/detail/884076?site
推荐阅读
相关标签
  

闽ICP备14008679号