Java发送websocket

WebSoketController

package com.iscas.base.biz.test.controller;

import com.iscas.templet.common.ResponseEntity;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.handler.annotation.MessageMapping;
import org.springframework.messaging.handler.annotation.SendTo;
import org.springframework.messaging.simp.SimpMessagingTemplate;
import org.springframework.messaging.simp.user.SimpUser;
import org.springframework.messaging.simp.user.SimpUserRegistry;
import org.springframework.web.bind.annotation.RestController;

import java.security.Principal;

/**
 * 如有要看例子,请打开注释
 *
 **/
@RestController
public class WebSoketDemoController {

    //spring提供的发送消息模板
    @Autowired
    private SimpMessagingTemplate messagingTemplate;

    @Autowired
    private SimpUserRegistry userRegistry;



    /*点对点通信*/
    @MessageMapping(value = "/P2P")
    public void templateTest(Principal principal) {
        int i = 1;
        for (SimpUser user : userRegistry.getUsers()) {
        }
        //发送消息给指定用户
        messagingTemplate.convertAndSendToUser(principal.getName(), "/queue/message","服务器主动推的数据");
    }

    /*广播*/
    @MessageMapping("/broadcast")
    @SendTo("/topic/getResponse")
    public ResponseEntity topic() throws Exception {
        return new ResponseEntity(200,"success");
    }

}

WebSocketStompConfig

import org.springframework.context.annotation.Configuration;
import org.springframework.messaging.simp.config.MessageBrokerRegistry;
import org.springframework.web.socket.config.annotation.EnableWebSocketMessageBroker;
import org.springframework.web.socket.config.annotation.StompEndpointRegistry;
import org.springframework.web.socket.config.annotation.WebSocketMessageBrokerConfigurer;

/**
 * @author [email protected]
 * @version 1.0
 * @date 2022/5/26 15:10
 */
@Configuration
@EnableWebSocketMessageBroker
public class WebSocketStompConfig implements WebSocketMessageBrokerConfigurer {

    /**
     * 注册stomp端点
     * @param registry
     */
    @Override
    public void registerStompEndpoints(StompEndpointRegistry registry) {

        // 允许使用socketJs方式访问 即可通过http://IP:PORT/xboot/ws来和服务端websocket连接
        registry.addEndpoint("/message/ws").setAllowedOrigins("*").withSockJS();
    }

    /**
     * 配置信息代理
     * @param registry
     */
    @Override
    public void configureMessageBroker(MessageBrokerRegistry registry) {

        // 订阅Broker名称 user点对点 topic广播即群发
        registry.enableSimpleBroker("/user", "/topic");
        // 全局(客户端)使用的消息前缀
        registry.setApplicationDestinationPrefixes("/app");
        // 点对点使用的前缀 无需配置 默认/user
        registry.setUserDestinationPrefix("/user");
    }
}

broadcast.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Websocket广播通信测试</title>
    <script src="http://cdn.bootcss.com/stomp.js/2.3.3/stomp.min.js"></script>
    <script src="https://cdn.bootcss.com/sockjs-client/1.1.4/sockjs.min.js"></script>
    <script>
        var socket = new SockJS("http://192.168.100.84:32088/message/ws");
        // var socket = new SockJS("http://192.168.100.84:7810/status/webSocketServer");
        // var socket = new SockJS('http://localhost:15674/stomp');
        var stompClient = Stomp.over(socket);
        window.onload = function () {
            connect();
        }
        //订阅消息
        function subscribe() {

            stompClient.subscribe('/topic/message/hdfs', function(response){
                console.log(response);
                // alert("/topic/getResponse 你接收到的消息为:" + response);
            });

        }
        function send() {
            stompClient.send("/app/broadcast", {},
                JSON.stringify({ 'name': 'testtest' }));
        }
        function connect() {

            stompClient.connect({
                    //这里可以改成token
                    Authorization: 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJleHAiOjIxOTg1NjQxNjAsImlhdCI6MTUzMTg5NzUwMCwidXNlcm5hbWUiOiJ6cXcxMSJ9.VFR2EKUx5BTYLDkDogiLA9LfNVoPjOzQ3rTWoEy7He4' // 携带客户端信息
                },
                function connectCallback(frame) {
                    // 连接成功时(服务器响应 CONNECTED 帧)的回调方法
                    alert("success");
                    subscribe();
                },
                function errorCallBack(error) {
                    // 连接失败时(服务器响应 ERROR 帧)的回调方法
                    alert("error");
                });
        }
        function disconnect() {
            if (stompClient != null) {
                stompClient.disconnect();
            }
//            setConnected(false);
            console.log("Disconnected");
        }
    </script>
</head>
<body>
<input type="text" id="info"/><button onclick="send();">发送</button>
</body>
</html>

你可能感兴趣的:(websocket,java,网络协议)