spring-websocket使用方法
spring-websocket使用方法
wankaiming 发表于10个月前
spring-websocket使用方法
  • 发表于 10个月前
  • 阅读 54
  • 收藏 0
  • 点赞 0
  • 评论 0

【腾讯云】如何购买服务器最划算?>>>   

1.pom.xml加入依赖包

<dependency>
	<groupId>org.springframework</groupId>
	<artifactId>spring-websocket</artifactId>
	<version>${spring.version}</version>
</dependency>
<dependency>
	<groupId>org.springframework</groupId>
	<artifactId>spring-messaging</artifactId>
	<version>${spring.version}</version>
</dependency>

2.配置web.xml

<servlet>
	<servlet-name>rest</servlet-name>
	<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
	<init-param>
		<param-name>contextConfigLocation</param-name>
		<param-value>classpath:spring.xml</param-value>
	</init-param>
	<load-on-startup>1</load-on-startup>
	<async-supported>true</async-supported>  <!-- 加入这一行 -->
</servlet>
<filter>
	<filter-name>encodingFilter</filter-name>
	<filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
	<init-param>
		<param-name>encoding</param-name>
		<param-value>UTF-8</param-value>
	</init-param>
	<init-param>
		<param-name>forceEncoding</param-name>
		<param-value>true</param-value>
	</init-param>
	<async-supported>true</async-supported> <!-- 加入这一行 -->
</filter>

3.配置websocket

@Configuration
@EnableWebMvc
@EnableWebSocketMessageBroker
public class WebSocketConfig extends AbstractWebSocketMessageBrokerConfigurer {

	@Override
	public void configureMessageBroker(MessageBrokerRegistry config) {
		//这句表示在topic和user这两个域上可以向客户端发消息
		config.enableSimpleBroker("/topic", "/user");
		//这句表示给指定用户发送(一对一)的主题前缀是“/user/”
		config.setUserDestinationPrefix("/user");
	}

	@Override
	public void registerStompEndpoints(StompEndpointRegistry registry) {
		//这个和客户端创建连接时的url有关
		registry.addEndpoint("/websocket").setAllowedOrigins("*").withSockJS();
	}

}

4.建立一个消息dto

public class MessageDto implements Serializable{
	
	private static final long serialVersionUID = -4953803885944191487L;
	
	private Date time;

	private Integer code;
	
	private String msg;

	public Date getTime() {
		return time;
	}

	public void setTime(Date time) {
		this.time = time;
	}

	public Integer getCode() {
		return code;
	}

	public void setCode(Integer code) {
		this.code = code;
	}

	public String getMsg() {
		return msg;
	}

	public void setMsg(String msg) {
		this.msg = msg;
	}
}

5.测试消息发送的地址

@RestController
@RequestMapping(value = "/test")
public class TestRest {
	
    @Autowired
    private SimpMessageSendingOperations simpMessageSendingOperations;
	
	/**
	 * 测试消息发送
	 * @return
	 */
    @NotNeedOauth
    @RequestMapping(value = "/pub",method = RequestMethod.GET)
    public Object praiseBeingList(){
    	
    	MessageDto msg_1 = new MessageDto();
    	msg_1.setTime(new Date());
    	msg_1.setCode(0);
    	msg_1.setMsg("点对点");
    	simpMessageSendingOperations.convertAndSendToUser("1", "/message", msg_1); //一对一发送,发送特定的客户端  
    	
    	MessageDto msg = new MessageDto();
    	msg.setTime(new Date());
    	msg.setCode(0);
    	msg.setMsg("广播");
    	simpMessageSendingOperations.convertAndSend("/topic/broadcast",msg); //广播  
    	

        Map<String,Object>  resultMap = new HashMap<>();
        resultMap.put("code","ok");
        return resultMap;
    }

}

6.前端页面

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html lang="en">
<head>
    <title>Hello WebSocket</title>
    <script src="http://cdn.bootcss.com/sockjs-client/1.1.1/sockjs.min.js"></script>
    <script src="http://cdn.bootcss.com/stomp.js/2.3.3/stomp.js"></script>
    <script src="http://cdn.bootcss.com/jquery/1.8.1/jquery.min.js"></script>
    <script type="text/javascript">
        var stompClient = null;
		
        function setConnected(connected) {
        	$("#connect").attr("disabled",connected);
        	$("#disconnect").attr("disabled",!connected);
        	$("#conversationDiv").css('visibility',connected ? 'visible' : 'hidden');
            $("#response").html("");
        }

        function connect() {
            var userid = 1;
            var socket = new SockJS("http://localhost:8080/websocket");
            stompClient = Stomp.over(socket);
            stompClient.connect({}, function(frame) {
                setConnected(true);
                console.log('Connected: ' + frame);
                stompClient.subscribe('/topic/broadcast', function(data){
                    console.log(data);
                    $("#response").text(data.body);
                });
               
                stompClient.subscribe('/user/' + userid + '/message',function(data){
                	console.log(data);
                	$("#response").text(data.body);
                });
            });
        }

        function disconnect() {
            if (stompClient != null) {
                stompClient.disconnect();
            }
            setConnected(false);
            console.log("Disconnected");
        }
        
    </script>
</head>
<body>
<div>
    <div>
        <button id="connect" onclick="connect();">Connect</button>
        <button id="disconnect" disabled="disabled" onclick="disconnect();">Disconnect</button>
    </div>
    <div id="conversationDiv">
        <p id="response"></p>
    </div>
</div>
</body>
</html>

7.先点击Connect按钮,建立websocket连接,然后访问http://localhost:8080/test/pub发布消息出来,这样页面就可以收到消息了

备注:如果用nginx作为前置代理,nginx 的 location需要加入下面的配置

proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection "upgrade";

共有 人打赏支持
wankaiming
粉丝 71
博文 224
码字总数 59096
×
wankaiming
如果觉得我的文章对您有用,请随意打赏。您的支持将鼓励我继续创作!
* 金额(元)
¥1 ¥5 ¥10 ¥20 其他金额
打赏人
留言
* 支付类型
微信扫码支付
打赏金额:
已支付成功
打赏金额: