Websocket

在springboot项目中引入websocket依赖

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

创建一个websocket服务点导出器

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.server.standard.ServerEndpointExporter;
 
@Configuration
public class WebsocketConfig {
    @Bean
    public ServerEndpointExporter getServerEndpointExporter(){
        return new ServerEndpointExporter();
    }
}

创建一个websocket服务类

import org.springframework.stereotype.Component;
 
import javax.websocket.OnClose;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.concurrent.CopyOnWriteArraySet;
 
@Component
@ServerEndpoint("/websocketurl")//设置websocket连接url,就是前端创建websocket需要提供的url
public class MyWebSocketService {
    private Session session;
    
    //存放所有的websocket连接
    private static CopyOnWriteArraySet<MyWebSocketService> myWebSocketServicesSet = new CopyOnWriteArraySet<>();
    
    //建立websocket连接时自动调用
    @OnOpen
    public void onOpen(Session session){
        this.session = session;
        myWebSocketServicesSet.add(this);
        System.out.println("有新的websocket连接进入,当前连接总数为" + myWebSocketServicesSet.size());
    }
 
    //关闭websocket连接时自动调用
    @OnClose
    public void onClose(){
        myWebSocketServicesSet.remove(this);
        System.out.println("连接断开,当前连接总数为" + myWebSocketServicesSet.size());
    }
 
    //websocket接收到消息时自动调用
    @OnMessage
    public void onMessage(String message){
        System.out.println("this:" + message);
    }
 
    //通过websocket发送消息
    public void sendMessage(String message){
        for (MyWebSocketService webSocketService : myWebSocketServicesSet){
            try {
                webSocketService.session.getBasicRemote().sendText(message);
            } catch (IOException e) {
                System.err.println(this + "发送消息错误:" + e.getClass() + ":" + e.getMessage());
            }
        }
    }
}

创建一个接收创建订单信息的控制器

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import xyz.syyrjx.websockettest.websocketService.MyWebSocketService;
 
import javax.annotation.Resource;
 
@Controller
public class MyController {
 
    @Resource
    MyWebSocketService webSocketService;
 
    @RequestMapping("/sendMessage")
    @ResponseBody
    public Object sendMessage(String msg){
        webSocketService.sendMessage(msg);
        return null;
    }
}

Comments

No comments yet. Why don’t you start the discussion?

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注