SpringBoot之Using WebSocket to build an interactive web application
2016-06-14 16:17
791 查看
通过 STOMP来简单实现WebSocket的交互。
1 服务端接收的消息model类
2 客户端接收的消息model类
3 controller类
说明:
The @MessageMapping annotation ensures that if a message is sent to destination “/hello”, then the greeting() method is called.
Internally, the implementation of the method simulates a processing delay by causing the thread to sleep for 3 seconds. This is to demonstrate that after the client sends a message, the server can take as long as it needs to process the message asynchronously. The client may continue with whatever work it needs to do without waiting on the response.
The return value is broadcast to all subscribers to “/topic/greetings” as specified in the @SendTo annotation.
4 STOMP消息配置
说明:
@EnableWebSocketMessageBroker enables WebSocket message handling, backed by a message broker.
The configureMessageBroker() method overrides the default method in WebSocketMessageBrokerConfigurer to configure the message broker. It starts by calling enableSimpleBroker() to enable a simple memory-based message broker to carry the greeting messages back to the client on destinations prefixed with “/topic”. It also designates the “/app” prefix for messages that are bound for @MessageMapping-annotated methods.
The **registerStompEndpoints() **method registers the “/hello” endpoint, enabling SockJS fallback options so that alternative messaging options may be used if WebSocket is not available. This endpoint, when prefixed with “/app”, is the endpoint that the GreetingController.greeting() method is mapped to handle.
5 客户端html
1 服务端接收的消息model类
package websocket.interactive.web.application.hello; public class HelloMessage { private String name; public String getName(){ return name; } }
2 客户端接收的消息model类
package websocket.interactive.web.application.hello; public class Greeting { private String content; public Greeting(String content){ this.content = content; } public String getContent(){ return content; } }
3 controller类
package websocket.interactive.web.application.hello; import org.springframework.messaging.handler.annotation.MessageMapping; import org.springframework.messaging.handler.annotation.SendTo; import org.springframework.stereotype.Controller; @Controller public class GreetingController { @MessageMapping("/hello") @SendTo("/topic/greetings") public Greeting greeting(HelloMessage message) throws InterruptedException{ Thread.sleep(500L); return new Greeting("Hello, " + message.getName() + "!"); } }
说明:
The @MessageMapping annotation ensures that if a message is sent to destination “/hello”, then the greeting() method is called.
Internally, the implementation of the method simulates a processing delay by causing the thread to sleep for 3 seconds. This is to demonstrate that after the client sends a message, the server can take as long as it needs to process the message asynchronously. The client may continue with whatever work it needs to do without waiting on the response.
The return value is broadcast to all subscribers to “/topic/greetings” as specified in the @SendTo annotation.
4 STOMP消息配置
package websocket.interactive.web.application.hello; import org.springframework.context.annotation.Configuration; import org.springframework.messaging.simp.config.MessageBrokerRegistry; import org.springframework.web.socket.config.annotation.AbstractWebSocketMessageBrokerConfigurer; import org.springframework.web.socket.config.annotation.EnableWebSocketMessageBroker; import org.springframework.web.socket.config.annotation.StompEndpointRegistry; @Configuration @EnableWebSocketMessageBroker public class WebSocketConfig extends AbstractWebSocketMessageBrokerConfigurer { @Override public void configureMessageBroker(MessageBrokerRegistry config) { config.enableSimpleBroker("/topic"); config.setApplicationDestinationPrefixes("/app"); } public void registerStompEndpoints(StompEndpointRegistry registry) { registry.addEndpoint("/hello").withSockJS(); } }
说明:
@EnableWebSocketMessageBroker enables WebSocket message handling, backed by a message broker.
The configureMessageBroker() method overrides the default method in WebSocketMessageBrokerConfigurer to configure the message broker. It starts by calling enableSimpleBroker() to enable a simple memory-based message broker to carry the greeting messages back to the client on destinations prefixed with “/topic”. It also designates the “/app” prefix for messages that are bound for @MessageMapping-annotated methods.
The **registerStompEndpoints() **method registers the “/hello” endpoint, enabling SockJS fallback options so that alternative messaging options may be used if WebSocket is not available. This endpoint, when prefixed with “/app”, is the endpoint that the GreetingController.greeting() method is mapped to handle.
5 客户端html
<!DOCTYPE html> <html> <head> <title>Hello WebSocket</title> <script src="sockjs-0.3.4.js"></script> <script src="stomp.js"></script> <script type="text/javascript"> var stompClient = null; function setConnected(connected) { document.getElementById('connect').disabled = connected; document.getElementById('disconnect').disabled = !connected; document.getElementById('conversationDiv').style.visibility = connected ? 'visible' : 'hidden'; document.getElementById('response').innerHTML = ''; } function connect() { var socket = new SockJS('/hello'); stompClient = Stomp.over(socket); stompClient.connect({}, function(frame) { setConnected(true); console.log('Connected: ' + frame); stompClient.subscribe('/topic/greetings', function(greeting){ showGreeting(JSON.parse(greeting.body).content); }); }); } function disconnect() { if (stompClient != null) { stompClient.disconnect(); } setConnected(false); console.log("Disconnected"); } function sendName() { var name = document.getElementById('name').value; stompClient.send("/app/hello", {}, JSON.stringify({ 'name': name })); } function showGreeting(message) { var response = document.getElementById('response'); var p = document.createElement('p'); p.style.wordWrap = 'break-word'; p.appendChild(document.createTextNode(message)); response.appendChild(p); } </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"> <label>What is your name?</label><input type="text" id="name" /> <button id="sendName" onclick="sendName();">Send</button> <p id="response"></p> </div> </div> </body> </html>
相关文章推荐
- 2015-2016网页设计趋势分析 Web Design of Trends
- Spring整合WebSocket应用示例(上)
- 浅析nodejs实现Websocket的数据接收与发送
- Spring整合websocket整合应用示例(下)
- 基于html5和nodejs相结合实现websocket即使通讯
- 基于node实现websocket协议
- Android中使用WebSocket实现群聊和消息推送功能(不使用WebView)
- php使用websocket示例详解
- php+html5基于websocket实现聊天室的方法
- Javascript WebSocket使用实例介绍(简明入门教程)
- java中实现兼容ie6 7 8 9的spring4+websocket
- HTML5之WebSocket入门3 -通信模型socket.io
- Java后端Tomcat实现WebSocket实例教程
- 使用JavaWeb webSocket实现简易的点对点聊天功能实例代码
- Spring和Websocket相结合实现消息的推送
- Python实现同时兼容老版和新版Socket协议的一个简单WebSocket服务器
- Python通过websocket与js客户端通信示例分析
- 使用 Nginx 代理 Socket.io/WebSocket 及 负载均衡配置
- IM 协议的分析和选取 (XMPP&WebSocket)
- WebSocket从零开始