WebSocket使用详解

       WebSocket一种网络通信协议,主要用于服务端和客户端双向通信,一般多于多人聊天、实时监控、消息推送等方面,客户端使用前端实现,本文不做描述,主要写一下webSocket服务端是怎么实现的。

1、引入依赖

pom.xml

<dependency>
	<groupId>org.springframework.boot</groupId>
	<artifactId>spring-boot-starter-websocket</artifactId>
</dependency>

2、往spring容器中注入 ServerEndpointExporter

webSocketConfig

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.socket.server.standard.ServerEndpointExporter;

@Configuration
public class WebSocketConfig {
    /*
    往spring容器中注入 ServerEndpointExporter
     */
    @Bean
    public ServerEndpointExporter serverEndpointExporter() {
        return new ServerEndpointExporter();
    }
}

3、Endpoint具体实现

import org.springframework.stereotype.Component;

import javax.websocket.*;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.concurrent.CopyOnWriteArraySet;

@ServerEndpoint(value = "/websocket")//WebSocket客户端建立连接的地址
@Component
public class WebSocketServlet {
    //用来存放每个客户端对应的MyWebSocket对象
    private static CopyOnWriteArraySet<WebSocketServlet> webSocketSet = new CopyOnWriteArraySet<WebSocketServlet>();
    private Session session = null;
    /*
    开启连接的操作
     */
    @OnOpen
    public void onOpen(Session session) throws IOException {
        this.session = session;
        webSocketSet.add(this);
        System.out.println(webSocketSet);
        try{
            sendMessage();
        }catch (IOException e){
            e.printStackTrace();
        }

    }

    /*
    连接关闭的操作
     */
    @OnClose
    public void onClose(){
        webSocketSet.remove(this);
    }

    /*
    给服务器发送消息,监听心跳
     */
    @OnMessage
    public void onMessage(String message){
        if(!message.equals("heartbeat")){
            try{
                session.getBasicRemote().sendText("你是"+session.getId()+",你输入的信息是:"+message);
            }catch (IOException e){
                e.printStackTrace();
            }
        }else{
            System.out.println("接收到客户端:"+session.getId()+"发送的消息"+message);
            try{
                session.getBasicRemote().sendText("heartbeat");//返回心跳信息
            }catch (IOException e){
                e.printStackTrace();
            }
        }


    }


    /*
    出错的操作
     */
    @OnError
    public void onError(Throwable error){
        System.out.println(error);
        error.printStackTrace();
    }

    /*
    自定义的方法,告诉前台数据库发生改变的数据
     */
    public void sendMessage() throws IOException{
        String meassage = "欢迎连接测试WebSocket!";
        session.getBasicRemote().sendText(meassage);
    }

4、启动服务

@SpringBootApplication(exclude = {DataSourceAutoConfiguration.class})
@ServletComponentScan
public class WebStudyApplication {

	public static void main(String[] args) {
		SpringApplication.run(WebStudyApplication.class, args);
	}

}

5、使用在线测试工具测试

WebSocket使用详解

参考:https://www.jianshu.com/p/161df01cc8af