赞
踩
目录
目录
6.对于WebSocketServer的中无法直接使用@Autowired注解获取对象的方法和使用方式
WebSocket是HTML5开始提供的一种在单个TCP连接上进行全双工通讯的协议。它允许服务端主动发送信息给客户端,是实现推送(Push)技术的一种非常流行的解决方案。
WebSocket的特点:
(1)全双工通信:与传统的HTTP请求-响应不同,WebSocket支持服务器和客户端之间的全双工通信。
(2)单连接:WebSocket连接一旦建立,就可以送和接收无数个消息。
(3)服务器主动推送:服务器可以主动发送信息给客户端,不需要客户端不断地询问服务器是否有新信息。
(4)持久连接:与传统的基于轮询(Polling)的推送技术相比,WebSocket连接一旦建立,就可以持续开放,减少了因频繁建立和关闭连接而造成的开销。
(5)协议升级:WebSocket协议通过握手过程从HTTP协议升级而来,其初始的握手请求是一个升级请求。
- <dependency>
- <groupId>org.springframework.boot</groupId>
- <artifactId>spring-boot-starter-websocket</artifactId>
- </dependency>
- package com.example.springbootudp.config;
-
- import org.springframework.context.annotation.Bean;
- import org.springframework.context.annotation.Configuration;
-
- import org.springframework.web.socket.server.standard.ServerEndpointExporter;
-
-
- @Configuration
- public class WebSocketConfig {
-
- @Bean
- public ServerEndpointExporter serverEndpointExporter(){
- return new ServerEndpointExporter();
- }
- }
-
- package com.example.springbootudp.server;
-
- import jakarta.websocket.*;
- import jakarta.websocket.server.ServerEndpoint;
- import org.springframework.stereotype.Component;
- import org.springframework.web.socket.TextMessage;
-
- import java.io.IOException;
-
- @ServerEndpoint(value = "/chat")
- @Component
- public class WebSocketServer {
- @OnOpen
- public void onOpen(Session session, EndpointConfig config){
-
- }
-
- @OnMessage
- public void onMessage(String message,Session session) throws IOException {
- System.out.println(message);
- // 发送响应给客户端
- TextMessage response = new TextMessage("Server response: " + message);
- System.out.println("response.getPayload():"+response.getPayload());
- session.getBasicRemote().sendText(response.getPayload());
-
- }
-
- @OnClose
- public void onClose(Session session){
-
- }
- }
- <!DOCTYPE html>
- <html>
- <head>
- <title>WebSocket Test</title>
- <script>
-
- const wsUri = "ws://localhost:8080/chat";
- const websocket = new WebSocket(wsUri);
-
- websocket.onopen = function() {
- console.log("WebSocket connection opened.");
- let message = document.getElementById('message').value;
- websocket.send(message);
- };
-
- websocket.onclose = function(evt) {
- console.log("WebSocket connection closed.");
- };
-
- websocket.onmessage = function(evt) {
- console.log("Received message:", event.data);
- // 可以在页面上显示接收到的消息
- var messages = document.getElementById('messages');
- var message = document.createElement('li');
- message.textContent = "Server: " + event.data;
- messages.appendChild(message);
- };
-
- websocket.onerror = function(evt) {
- console.log("WebSocket Error: " + evt.data);
- };
-
- // 修改后的 sendWebSocket 函数
- function sendWebSocketMessage() {
- // 确保在发送消息时连接已经打开
- if (websocket.readyState === WebSocket.OPEN) {
- let message = document.getElementById('message').value;
- websocket.send(message);
-
- } else {
- alert("WebSocket connection is not open.");
- }
- }
-
- </script>
- </head>
- <body>
-
- <ul id="messages"></ul>
- <input type="text" id="message" placeholder="请输入消息">
- <button onclick="sendWebSocketMessage()">发送消息</button>
-
- </body>
- </html>
只需要将发送单条数据的server和html修改部分代码即可
- @ServerEndpoint(value = "/chat")
- @Component
- public class WebSocketServer {
- // ... 其他代码 ...
-
- @OnMessage
- public void onMessage(String message, Session session) throws IOException {
- try {
- // 解析 JSON 字符串
- Object obj = JSON.parse(message);
-
- // 根据需要处理 obj,假设您需要处理的是一个带有 type 和 content 的消息
- String type = (String) obj.get("type");
- String content = (String) obj.get("content");
-
- System.out.println("Received message: " + message);
- // 可能的响应处理
- if ("message".equals(type)) {
- // 处理消息内容
- System.out.println("Content: " + content);
- }
-
- // 发送响应给客户端
- TextMessage response = new TextMessage(JSON.stringify({"type": "response", "content": "Server response to JSON"}));
- session.getBasicRemote().sendText(response.getPayload());
-
- } catch (JSONException e) {
- e.printStackTrace();
- // 处理解析错误
- }
- }
-
- // ... 其他代码 ...
- }
- <script>
- // ... 其他代码 ...
-
- function sendWebSocketMessage() {
- // 创建要发送的数据对象
- var messageObject = {
- type: "message",
- content: document.getElementById('message').value
- };
-
- // 将对象转换为 JSON 字符串
- var messageJSON = JSON.stringify(messageObject);
-
- // 确保在发送消息时连接已经打开
- if (websocket.readyState === WebSocket.OPEN) {
- websocket.send(messageJSON); // 发送 JSON 字符串
-
- } else {
- alert("WebSocket connection is not open.");
- }
- }
-
- // ... 其他代码 ...
- </script>
- package com.example.springbootudp.server;
-
- import jakarta.websocket.*;
- import jakarta.websocket.server.ServerEndpoint;
- import org.springframework.stereotype.Component;
- import org.springframework.web.socket.TextMessage;
-
- import java.io.IOException;
-
- @ServerEndpoint(value = "/chat")
- @Component
- public class WebSocketServer {
-
- private static MessageService messageService;
-
- @Autowired
- public void setWebSocketServer(MessageService messageService){
- WebSocketServer.messageService =messageService;
-
- }
-
- @OnOpen
- public void onOpen(Session session, EndpointConfig config){
-
- }
-
- @OnMessage
- public void onMessage(String message,Session session) throws IOException {
- WebSocketServer.messageService.getById();
-
- }
-
- @OnClose
- public void onClose(Session session){
-
- }
- }
赞
踩
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。