WebSocket

126 阅读1分钟

客户端

if(window.WebSocket) {
	var url =  "ws://localhost:8080/connect";
	var ws = new WebSocket(url);
}
    
ws.onopen = function() {
    console.log("连接建立");
}

ws.onmessage = function(evt) {
    console.log("接收到消息" + evt.data);
}

ws.onerror = function() {
    console.log("连接错误");
}

ws.onclose = function() {
    console.log("连接关闭");
}

if(ws.readyState == WebSocket.OPEN) {
    ws.send("Hello啊")
}

服务端

导入依赖

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

配置类

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

实现类

@Component
@ServerEndpoint("/test")
public class TestEndpoing {
    
    @OnMessage
    public void onMessage(String message, Session session) {
        System.out.println("接收到消息");
       session.getBasicRemote().sendText(message); 
    }
    
    @OnOpen
    public void onOpen(Session session) {
        System.out.println("连接建立");
    }
    
    @OnClose
    public void onClose(Session session) {
        System.out.println("连接关闭");
    }
    
    @OnError
    public void onError(Session session, Throwable error) {
        System.out.println("连接出错");
    }
}