Springboot based WebSocket achieve back-end message push

  • As business needs, the system in the background to add message push functionality, so go online access to relevant information, but information on the Internet are running in the front and rear end of a project, before and after the end of the separation now, so I toss myself a bit, in case to a lot of the pit.
  • Code is copied from the blog over the Internet, above all, the configuration file:
@Configuration
// @EnableWebSocketMessageBroker注解用于开启使用STOMP协议来传输基于代理(MessageBroker)的消息,这时候控制器(controller)
// 开始支持@MessageMapping,就像是使用@requestMapping一样。
@EnableWebSocketMessageBroker
public class WebSocketConfig implements WebSocketMessageBrokerConfigurer, BaseLoggerService {

    private Session session;

    @Override
    public void registerStompEndpoints(StompEndpointRegistry stompEndpointRegistry) {
        //注册一个Stomp的节点(endpoint),并指定使用SockJS协议,其中setAllowedOrigins是设置跨域的
        stompEndpointRegistry.addEndpoint("/webSocketEndPoint").setAllowedOrigins("*").withSockJS();
        // 如果要使用Java代码来连接Websocket需要使用如下配置,这段代码是翻墙去StackOverflow上面找到的,用来测试使用Java代码连接websocket
        // stompEndpointRegistry.addEndpoint("/webSocketEndPoint").setHandshakeHandler(new DefaultHandshakeHandler(new TomcatRequestUpgradeStrategy())).setAllowedOrigins("*");
    }

    @Override
    public void configureMessageBroker(MessageBrokerRegistry registry) {
        //服务端发送消息给客户端的域,多个用逗号隔开
        registry.enableSimpleBroker("/topic", "/user");
        //定义一对一推送的时候前缀
        registry.setUserDestinationPrefix("/user");
        //定义websoket前缀
        registry.setApplicationDestinationPrefixes("/ws-push");
    }
}
  • The second is websocket service sends the message:
@Service
public class WebSocketMessageServiceImpl implements WebSocketMessageService {

    @Autowired
    private SimpMessagingTemplate simpMessagingTemplate;

    /**
     * 广播
     * 发给所有在线用户
     *
     * @param msg
     */
    public void sendMsg(WebSocketMessage msg) {
        simpMessagingTemplate.convertAndSend("/topic/getResponse", msg);
    }

    /**
     * 发送给指定用户
     *
     * @param users
     * @param msg
     */
    private void send2Users(String users, final Object msg) {
        simpMessagingTemplate.convertAndSendToUser(users, "/msg", msg);
    }

	/**
     * 根据消息类型发送不同的内容
     *
     * @param param
     */
    @Override
    public void sendAndFormatToUsers(Map param) {
         // 发送消息到前端,可以在这里通过自定义字符串向前端发送指定用户发送消息
         String newUser = "webSocket";
         // 点对点发送消息
         send2Users(newUser, message);
         logger.info(message);
    }	
}
  • Front-end code, you need to import js three files:
<html>
<head>
    <meta charset="UTF-8">
    <title>Hello topic</title>
    <script src="./sock.js"></script>
    <script src="./stomp.js"></script>
    <script src="./jquery.min.js"></script>   
    <script type="text/javascript">
        var stompClient = null;
        function setConnected(connected){
            document.getElementById("connect").disabled = connected;
            document.getElementById("disconnect").disabled = !connected;
            $("#response").html();
        }
        function connect() {
            console.log("111111111111");
            // 这里的端口需要写自己项目的端口
            var socket = new SockJS("http://localhost:7086/webSocketEndPoint");
            stompClient = Stomp.over(socket);
            stompClient.connect({}, function(frame) {
                setConnected(true);
                console.log('Connected: ' + frame);
                // 这里的webSocket与后端的自定义字符串相匹配,用来接收后台发送的指向消息
                stompClient.subscribe('/user/webSocket/msg', function(response){
                    var response1 = document.getElementById('response');
                    var p = document.createElement('p');
                    p.style.wordWrap = 'break-word';
                    p.appendChild(document.createTextNode(response.body));
                    response1.appendChild(p);
                });
            });
        }

        function disconnect() {
            if (stompClient != null) {
                stompClient.disconnect();
            }
            setConnected(false);
            console.log("Disconnected");
        }
        
        function sendName() {
            var name = document.getElementById('name').value;
            console.info(1111111111);
            stompClient.send("/subscribe", {}, JSON.stringify({ 'name': name }));
        }
    </script>
</head>
<body onload="disconnect()">
<noscript><h2 style="color: #ff0000">Seems your browser doesn't support Javascript! Websocket relies on Javascript being enabled. Please enable
    Javascript and reload this page!</h2></noscript>
<div>
    <div>
        <button id="connect" onclick="connect();">Connect</button>
        <button id="disconnect" disabled="disabled" onclick="disconnect();">Disconnect</button>
    </div>
    <div id="conversationDiv">
        <labal>名字</labal><input type="text" id="name" />
        <button id="sendName" onclick="sendName();">Send</button>
        <p id="response"></p>
    </div>
</div>

</body>
</html>
  • Code is ready, then start Springboot project, then use Nginx open Html page, I have not used Nginx Html open access, the front end will complain, as follows:

Error Messages

  • When sending a message, write their own test class, you can call the sendAndFormatToUsers method.
  • Then I want to test the maximum number of connections websocket, and went online to find some java code of connection websocket:
@ClientEndpoint
public class WebSocketTest {

    private String deviceId;

    private Session session;

    public WebSocketTest () {

    }

    public WebSocketTest (String deviceId) {
        this.deviceId = deviceId;
    }

    protected boolean start() {
        WebSocketContainer container = ContainerProvider.getWebSocketContainer();
        String uri = "ws://localhost:7086/webSocketEndPoint";
        System.out.println("Connecting to " + uri);
        try {
            session = container.connectToServer(WebSocketTest.class, URI.create(uri));
            System.out.println("count: " + deviceId);
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
        return true;
    }

    public static void main(String[] args) {
        for (int i = 1; i< 50000; i++) {
            WebSocketTest wSocketTest = new WebSocketTest(String.valueOf(i));
            if (!wSocketTest.start()) {
                System.out.println("测试结束!");
                break;
            }
        }
    }

}
  • After testing, the maximum number of websocket connected to the current project can support 10,000, perfectly adequate project used, but through access to information to know, can increase the number of connections by configuring the maximum number of connections tomcat, when you can be 20,000 when the maximum number of connections configured the number of connections increased to 16,000.
Published 24 original articles · won praise 14 · views 60000 +

Guess you like

Origin blog.csdn.net/biubiu2it/article/details/86169196