• websocket--技术文档--spring后台+vue基本使用


    阿丹:

            给大家分享一个可以用来进行测试websocket的网页,个人觉得还是挺好用的.

    WebSocket在线测试工具

    还有一个小家伙ApiPost也可以进行使用websocket的测试。

    本文章只是基本使用--给大家提供思路简单实现!!

    使用spring-boot建立一个服务端

    在Spring Boot中使用WebSocket建立服务端,可以按照以下步骤进行:

    1. 确保的Spring Boot项目已经创建并配置好。
    2. 在项目的pom.xml文件中,添加WebSocket的依赖。
    1. <dependency>
    2. <groupId>org.springframework.boot</groupId>
    3. <artifactId>spring-boot-starter-websocket</artifactId>
    4. </dependency>
    1. 创建一个WebSocket配置类,用于配置WebSocket服务器。
    1. import org.springframework.context.annotation.Configuration;
    2. import org.springframework.web.socket.config.annotation.EnableWebSocket;
    3. import org.springframework.web.socket.config.annotation.WebSocketConfigurer;
    4. import org.springframework.web.socket.config.annotation.WebSocketHandlerRegistry;
    5. @Configuration
    6. @EnableWebSocket
    7. public class WebSocketConfig implements WebSocketConfigurer {
    8. @Override
    9. public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) {
    10. registry.addHandler(myHandler(), "/websocket/test/{sid}");
    11. }
    12. @Bean
    13. public MyHandler myHandler() {
    14. return new MyHandler();
    15. }
    16. }
    1. 创建一个WebSocket处理器类(MyHandler),用于处理WebSocket消息。
    1. import org.springframework.web.socket.TextMessage;
    2. import org.springframework.web.socket.WebSocketSession;
    3. import org.springframework.web.socket.handler.TextWebSocketHandler;
    4. public class MyHandler extends TextWebSocketHandler {
    5. @Override
    6. public void handleTextMessage(WebSocketSession session, TextMessage message) {
    7. // 处理接收到的文本消息
    8. System.out.println("Received message: " + message.getPayload());
    9. }
    10. @Override
    11. public void onOpen(WebSocketSession session) {
    12. // 连接建立成功调用的方法
    13. System.out.println("New client connected: " + session.getPrincipal());
    14. }
    15. }
    1. 在需要使用WebSocket的地方,例如控制器类,注入WebSocketSession,并使用sendMessage方法发送消息。

    以上就是在Spring Boot中使用WebSocket建立服务端的步骤。注意,还需要根据实际情况进行进一步的配置和开发。

    使用spring-boot建立一个客户端

    要使用Spring Boot建立一个客户端,可以按照以下步骤进行:

    1. 确保的Spring Boot项目已经创建并配置好。
    2. 在项目的pom.xml文件中,添加Spring WebSocket的依赖。
    1. <dependency>
    2. <groupId>org.springframework.boot</groupId>
    3. <artifactId>spring-boot-starter-websocket</artifactId>
    4. </dependency>
    1. 创建一个WebSocket配置类,用于配置WebSocket客户端。
    1. import org.springframework.context.annotation.Configuration;
    2. import org.springframework.web.socket.config.annotation.EnableWebSocketClient;
    3. import org.springframework.web.socket.config.annotation.WebSocketConfigurer;
    4. import org.springframework.web.socket.config.annotation.WebSocketClientConfigurer;
    5. import org.springframework.web.socket.client.WebSocketClient;
    6. import org.springframework.web.socket.client.standard.StandardWebSocketClient;
    7. import org.springframework.web.socket.handler.TextWebSocketHandler;
    8. @Configuration
    9. @EnableWebSocketClient
    10. public class WebSocketClientConfig implements WebSocketClientConfigurer {
    11. @Override
    12. public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) {
    13. registry.addHandler(myHandler(), "/websocket/test/{sid}");
    14. }
    15. @Bean
    16. public WebSocketClient myWebSocketClient() {
    17. return new StandardWebSocketClient();
    18. }
    19. @Bean
    20. public MyHandler myHandler() {
    21. return new MyHandler();
    22. }
    23. }
    1. 创建一个WebSocket处理器类(MyHandler),用于处理WebSocket消息。
    1. import org.springframework.web.socket.TextMessage;
    2. import org.springframework.web.socket.WebSocketSession;
    3. import org.springframework.web.socket.handler.TextWebSocketHandler;
    4. public class MyHandler extends TextWebSocketHandler {
    5. @Override
    6. public void handleTextMessage(WebSocketSession session, TextMessage message) {
    7. // 处理接收到的文本消息
    8. System.out.println("Received message: " + message.getPayload());
    9. }
    10. }
    1. 创建一个用于发送消息的控制器类。
    1. import org.springframework.beans.factory.annotation.Autowired;
    2. import org.springframework.context.ApplicationListener;
    3. import org.springframework.messaging.handler.annotation.MessageMapping;
    4. import org.springframework.messaging.handler.annotation.SendTo;
    5. import org.springframework.messaging.simp.SimpMessageSendingOperations;
    6. import org.springframework.social.connect.*;
    7. import org.springframework.web.*;
    8. import org.springframework.*;
    9. import java.util.*;
    10. @RestController("/")
    11. @RequestMapping("/")
    12. public class WebSocketController {
    13. @Autowired
    14. private SimpMessageSendingOperations operations;
    15. @Autowired
    16. private WebSocketConnectionEstablishedEvent event;
    17. public void setEvent(WebSocketConnectionEstablishedEvent event) {
    18. this.event = event;
    19. }
    20. @MessageMapping("/greet/{name}")
    21. @SendTo("/topic/greet")
    22. public String greet(@PathVariable String name) {
    23. return "Hello, " + name + "!";
    24. }
    25. @RequestMapping(value = "/error", produces = MediaType.APPLICATION_JSON_VALUE)
    26. public Map handleError(HttpServletRequest request) {
    27. Map model = new HashMap<>();
    28. model.put("timestamp", new Date());
    29. model.put("status", HttpStatusInitializer.__getHttpStatus(request, NullPointerException));
    30. model.put("error", "Internal Server Error");
    31. model.put("exception", NullPointerException.__toString());
    32. model.put("message", "Something bad happened, please try again!");
    33. model.put("path", request.__toString());
    34. return model;
    35. }
    36. @Autowired
    37. private WebSocketClient myWebSocketClient;
    38. @Autowired
    39. private MyHandler myHandler;
    40. @Autowired
    41. private ConnectionRepository connectionRepository;
    42. @Autowired
    43. private AuthenticationRepository authenticationRepository;
    44. public void sendMessageToUser(@PathVariable String name, @RequestParam String message) {
    45. Iterable> connections = connectionRepository.findConnections(String FacebookMarker.ID);
    46. for (Connection connection : connections) {
    47. if (connection.getProvider().getId().equals(String FacebookMarker.ID) && connection.getDisplayName().equals(name)) {
    48. connectionRepository.createSendToUserChannel(connection.getId()).send(MessageBuilder.withPayload(message).build());
    49. break;
    50. }
    51. }
    52. }
    53. }

    在上述代码中,我添加了一个sendMessageToUser方法,它使用connectionRepository查找与指定用户名匹配的连接,然后通过向该用户的个人通道发送消息来向该用户发送消息。请注意,这里假设您已经实现了与Facebook的连接,并且使用FacebookMarker作为提供者的标识符。可以根据需要进行相应的调整。

    使用vue来订阅连接成为一个websocket客户端

    要在Vue中订阅WebSocket连接并成为客户端,你可以按照以下步骤进行操作:

    1. 安装WebSocket库:首先,你需要下载并安装WebSocket库。你可以使用npm或yarn来安装。在终端中运行以下命令来安装webstomp-client库:
    npm install webstomp-client
    
    1. 创建一个WebSocket连接:在Vue组件中,你需要创建一个WebSocket连接。你可以在组件的created()钩子函数中创建连接。以下是一个示例代码片段:
    1. <template>
    2. <div>
    3. div>
    4. template>
    5. <script>
    6. import WebSocket from 'webstomp-client';
    7. export default {
    8. name: 'WebSocketClient',
    9. data() {
    10. return {
    11. socket: null,
    12. };
    13. },
    14. created() {
    15. this.initializeWebSocket();
    16. },
    17. methods: {
    18. initializeWebSocket() {
    19. this.socket = new WebSocket('wss://your-websocket-url'); // 使用你的WebSocket URL
    20. this.socket.onconnect = () => {
    21. console.log('WebSocket connected');
    22. };
    23. this.socket.onerror = (error) => {
    24. console.error('WebSocket error:', error);
    25. };
    26. this.socket.onclose = () => {
    27. console.log('WebSocket disconnected');
    28. };
    29. this.socket.onmessage = (message) => {
    30. console.log('Received message:', message);
    31. };
    32. },
    33. },
    34. };
    35. script>

    在上述代码中,我们首先导入WebSocket库,并在created()钩子函数中初始化WebSocket连接。你可以将wss://your-websocket-url替换为实际的WebSocket服务器URL。然后,我们定义了连接的回调函数,包括onconnectonerroroncloseonmessage。这些回调函数将在相应的WebSocket事件发生时执行。 3. 处理WebSocket消息:当从WebSocket接收消息时,你可以在onmessage回调函数中处理接收到的消息。你可以根据需要执行相应的操作,例如更新Vue组件的状态或触发其他行为。在上述示例代码中,我们只是简单地打印接收到的消息。 4. 发送WebSocket消息:要发送消息到WebSocket服务器,你可以使用WebSocket的send()方法。在Vue组件中,你可以定义一个方法来发送消息,并在需要发送消息时调用该方法。以下是一个示例代码片段:

    1. <template>
    2. <div>
    3. <button @click="sendMessage">Send Messagebutton>
    4. div>
    5. template>
    6. <script>
    7. import WebSocket from 'webstomp-client';
    8. export default {
    9. name: 'WebSocketClient',
    10. data() {
    11. return {
    12. socket: null,
    13. };
    14. },
    15. created() {
    16. this.initializeWebSocket();
    17. },
    18. methods: {
    19. initializeWebSocket() { /* ... */ }, // WebSocket连接初始化代码省略
    20. sendMessage() {
    21. const message = 'Hello, WebSocket Server!'; // 待发送的消息内容
    22. this.socket.send(message); // 发送消息到WebSocket服务器
    23. },
    24. },
    25. };
    26. script>

    在上述代码中,我们添加了一个按钮,并在点击时调用sendMessage()方法。该方法使用WebSocket的send()方法发送消息到服务器。请注意,你需要将实际的消息内容替换为'Hello, WebSocket Server!'

  • 相关阅读:
    VUE | key的内部原理、Vue监测数据的原理、Vue.set()和vm.$set()的使用
    Java智慧工地信息化管理平台源码,依托计算机信息、网络通讯、物联网、系统集成及云计算技术建立
    不会接口测试?用Postman轻松入门(六)——Post请求xml格式
    android8.1中用libtinyalsa编写sound-hal驱动
    【Educoder作业】问题求解——网页数据获取
    HTTP请求过程、浏览器开发者工具使用介绍、请求头与响应头(常见响应状态码)
    【Linux】进程概念(万字详解)—— 冯诺依曼体系结构 | 操作系统 | 进程
    英语单词(五)
    探索 Electron Egg:构建跨平台桌面应用的理想选择
    1.4_16 Axure RP 9 for mac 高保真原型图 - 案例15 【动态面板-滚动条5】深色模式 - 按钮效果升级
  • 原文地址:https://blog.csdn.net/weixin_72186894/article/details/132678845