• WebScoket


    一、前端页面

    1. html>
    2. <html lang="en">
    3. <head>
    4. <meta charset="UTF-8">
    5. <title>webSockettitle>
    6. <style type="text/css">
    7. style>
    8. head>
    9. <body>
    10. <h1>WebSocketh1>
    11. <input type="button" onclick="websocket.send('666666666')" value="点我发消息"/>
    12. body>
    13. <script type="application/javascript">
    14. var websocket = {
    15. send: function (str) {
    16. }
    17. };
    18. window.onload = function () {
    19. if (!'WebSocket' in window) return;
    20. webSocketInit();
    21. };
    22. function webSocketInit() {
    23. websocket = new WebSocket("ws://localhost:8081//websocket/socket");
    24. //成功建立连接
    25. websocket.onopen = function () {
    26. websocket.send("成功连接到服务器");
    27. };
    28. //接收到消息
    29. websocket.onmessage = function (event) {
    30. console.log(event.data)
    31. };
    32. //连接发生错误
    33. websocket.onerror = function () {
    34. alert("WebSocket连接发生错误");
    35. };
    36. //连接关闭
    37. websocket.onclose = function () {
    38. alert("WebSocket连接关闭");
    39. };
    40. //监听窗口关闭事件,当窗口关闭时,主动关闭websocket连接
    41. window.onbeforeunload = function () {
    42. websocket.close()
    43. };
    44. }
    45. script>
    46. html>

    二、后端代码

            2.1 maven引入

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

            2.2 配置类

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

            2.3 接收实现类

    1. import org.springframework.stereotype.Component;
    2. import javax.websocket.*;
    3. import javax.websocket.server.ServerEndpoint;
    4. import java.io.IOException;
    5. import java.util.concurrent.CopyOnWriteArraySet;
    6. @Component
    7. @ServerEndpoint("/websocket/socket") //暴露的ws应用的路径
    8. public class WebSocket {
    9. //concurrent包下线程安全的Set
    10. private static final CopyOnWriteArraySet SESSIONS = new CopyOnWriteArraySet<>();
    11. private Session session;
    12. @OnOpen
    13. public void onOpen(Session session) {
    14. this.session = session;
    15. SESSIONS.add(this);
    16. System.out.println(String.format("成功建立连接~ 当前总连接数为:%s", SESSIONS.size()));
    17. System.out.println(this);
    18. }
    19. @OnClose
    20. public void onClose() {
    21. SESSIONS.remove(this);
    22. System.out.println(String.format("成功关闭连接~ 当前总连接数为:%s", SESSIONS.size()));
    23. }
    24. @OnMessage
    25. public void onMessage(String message, Session session) {
    26. System.out.println(message);
    27. }
    28. @OnError
    29. public void onError(Session session, Throwable error) {
    30. System.out.println("发生错误");
    31. error.printStackTrace();
    32. }
    33. /**
    34. * 指定发消息
    35. *
    36. * @param message
    37. */
    38. public void sendMessage(String message) {
    39. try {
    40. this.session.getBasicRemote().sendText(message);
    41. } catch (IOException e) {
    42. e.printStackTrace();
    43. }
    44. }
    45. /**
    46. * 群发消息
    47. *
    48. * @param message
    49. */
    50. public static void fanoutMessage(String message) {
    51. SESSIONS.forEach(ws -> ws.sendMessage(message));
    52. }
    53. }

     

     

  • 相关阅读:
    隐藏底部任务栏图标的方法
    MATLAB算法实战应用案例精讲-【图像处理】SLAM技术详解(应用篇)
    虚数是什么
    STM32开发(三十)STM32F103 数据手册 —— 模拟/数字转换 DAC 详解
    java酒店管理系统设计与实现计算机毕业设计MyBatis+系统+LW文档+源码+调试部署
    供应链和物流的自动化新时代
    JavaScript之void 0 === undefined
    RabbitMQ 延时消息实现方式
    #Powerbi 1分钟学会,利用AI,为powerbi报表进行高端颜色设计
    冥想第九百四十八天
  • 原文地址:https://blog.csdn.net/weixin_51722520/article/details/133377584