0


springboot 集成webSocket

1、什么是webSocket?

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

1.新建config包,创建WebSocketConfig类

@Configuration
public class WSConfiguration {
    @Bean
    public ServerEndpointExporter serverEndpointExporter(){
        return new ServerEndpointExporter();
    }
}
​

2.新建service包,创建WebSocketServer类

@Component
@ServerEndpoint("/websocket")
public class WebSocketServer {
    //准备一个内部安全的集合 存放所有用户的websocket服务
    private static CopyOnWriteArraySet<WebSocketServer> wsset =  new CopyOnWriteArraySet<>();
    private Session session;
    @OnOpen
    public void opOpen(Session session){
        this.session=session;
        //将自身填充到set集合中 这个集合是所有客户端websocket的集合
​
        wsset.add(this);
        sendMsg();
​
​
    }
    @OnClose
    public void onClose(){
        //将自己从set集合中删除
         wsset.remove(this);
    }
    @OnError
    public void onError(Session session,Throwable error){
        System.out.println(this+"发生错误了");
    }
​
    //客户端发来消息
    @OnMessage
    public void onMessage(String clientMsg, Session session){
        System.out.println("来自客户端的信息+“。。。。。。。。。”===》"+clientMsg);
        //每隔一秒给你推送一条当前时间信息
​
    }
​
    private void sendMsg(){
​
        try {
            while(true){
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                String time =sdf.format(new Date());
                //发送数据
                this.session.getBasicRemote().sendText(time);
                Thread.sleep(1000);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
​
​
}
​

3.controller层加注解

@SpringBootApplication
@EnableWebSocket
public class MywebsocketApplication {
​
    public static void main(String[] args) {
        SpringApplication.run(MywebsocketApplication.class, args);
    }
​
}
​

4在resources下编写HTMl

<html>
    <head>
    </head>
    <body>
        <div id="time"></div>
​
        <script type="text/javascript">
            //new WebSocket
            var webSocket = new  WebSocket("ws://localhost:8080/websocket");
            webSocket.onopen = function () {
​
            }
​
            webSocket.onopen=function () {
​
            }
            webSocket.onclose=function () {
​
            }
            webSocket.οnerrοr=function () {
​
            }
            webSocket.onmessage=function (msg) {
                    document.getElementById("time").innerHTML=msg.data;
            }
        </script>
​
    </body>
​
</html>

5网页访问

http://localhost:8080/

6 WebSocketServer同步发送消息

package com.kgc.mywebsocket.commons;
​
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;
​
import javax.websocket.*;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.CopyOnWriteArraySet;
@Component
@ServerEndpoint("/websocket")
public class WebSocketServer {
    //准备一个内部安全的集合 存放所有用户的websocket服务
    private static CopyOnWriteArraySet<WebSocketServer> wsset =  new CopyOnWriteArraySet<>();
    private Session session;
    @OnOpen
    public void opOpen(Session session){
        this.session=session;
        //将自身填充到set集合中 这个集合是所有客户端websocket的集合
​
        wsset.add(this);
//        sendMsg();
​
​
    }
    @OnClose
    public void onClose(){
        //将自己从set集合中删除
         wsset.remove(this);
    }
    @OnError
    public void onError(Session session,Throwable error){
        System.out.println(this+"发生错误了");
    }
​
    //客户端发来消息
    @OnMessage
    public void onMessage(String clientMsg, Session session){
        System.out.println("来自客户端的信息+“。。。。。。。。。”===》"+clientMsg);
        //每隔一秒给你推送一条当前时间信息
        sendAllClient(clientMsg);
​
    }
​
    private void sendMsg(){
​
        try {
            while(true){
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                String time =sdf.format(new Date());
                //发送数据
                this.session.getBasicRemote().sendText(time);
                Thread.sleep(1000);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
​
    private void sendAllClient(String msg){
        try {
            for(WebSocketServer wss:wsset){
                wss.session.getBasicRemote().sendText(msg);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
​

7 html同步发送消息

<meta http-equiv="Content-Type" content="text/html;charset=utf-8"/>
<html>
    <head>
    </head>
    <body>
        <div id="time"></div>
        ==========
        <input type="text" id="txtMsg"/>
        ==========
        <br/>
        <button type="button" οnclick="sendMsg()">发送消息</button>
        <br/>
        <script type="text/javascript">
            //new WebSocket
            var webSocket = new  WebSocket("ws://localhost:8080/websocket");
            function sendMsg(){
                 var txt =document.getElementById("txtMsg").value;
                 webSocket.send(txt);
            }
            webSocket.onopen = function () {
​
            }
            webSocket.onclose=function () {
​
            }
            webSocket.οnerrοr=function () {
​
            }
            webSocket.onmessage=function (msg) {
                    document.getElementById("time").innerHTML=msg.data;
            }
        </script>
​
    </body>
​
</html>
http://localhost:8080/


本文转载自: https://blog.csdn.net/just_learing/article/details/125899260
版权归原作者 kjshuan 所有, 如有侵权,请联系我们删除。

“springboot 集成webSocket”的评论:

还没有评论