websocketsocketJs
  服务器端推送技术在web开发中⽐较常⽤,可能早期很多⼈的解决⽅案是采⽤ajax向服务器轮询消息,这种⽅式的轮询频率不好控制,所以⼤⼤增加了服务器的压⼒,后来有了下⾯的⽅案:当客户端向服务器发送请求时,服务器端会抓住这个请求不放,等有数据更新的时候才返回给客户端,当客户端接收到数据后再次发送请求,周⽽复始,这样就⼤⼤减少了请求次数,减轻了服务器的压⼒,当前主要有
SSE(Server Send Event 服务器端事件发送)的服务器端推送和基于Servlet3.0+异步⽅法特性实现的服务器端推送。⽽本次我将利⽤webSokcet实现服务器端消息推送。话不多说上代码:
  1、l,新建springboot项⽬,加⼊webSocket启动包spring-boot-starter-websocket;
  2、WebSocketConfig
ample.demo.websocket;
import t.annotation.Configuration;
import fig.MessageBrokerRegistry;
import org.springframework.fig.annotation.AbstractWebSocketMessageBrokerConfigurer;
import org.springframework.fig.annotation.EnableWebSocketMessageBroker;
import org.springframework.fig.annotation.StompEndpointRegistry;
@Configuration
@EnableWebSocketMessageBroker  //注解开启STOMP协议来传输基于代理的消息,此时控制器⽀持使⽤@MessageMapping
public class WebSocketConfig extends AbstractWebSocketMessageBrokerConfigurer {
@Override
public void configureMessageBroker(MessageBrokerRegistry config) {
}
@Override
public void registerStompEndpoints(StompEndpointRegistry registry) {
registry.addEndpoint("/webServer").withSockJS();
registry.addEndpoint("/queueServer").withSockJS();//注册两个STOMP的endpoint,分别⽤于⼴播和点对点
}
}
  3、接收消息类:ReceiveMessage
ample.demo.websocket;
public class ReceiveMessage {
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
  4、响应消息类:ResponseMessage
ample.demo.websocket;
public class ResponseMessage {
private String id;
private String name;
private String content;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getContent() {
websocket和socketreturn content;
}
public void setContent(String content) {
}
public ResponseMessage(String id, String name, String content) {
super();
this.id = id;
this.name = name;
}
}
  5、控制器类:SubController
ample.demo.websocket;
import org.springframework.beans.factory.annotation.Autowired;
import ssaging.handler.annotation.MessageMapping;
import ssaging.simp.SimpMessagingTemplate;
import org.springframework.stereotype.Controller;
@Controller
public class SubController {
@Autowired
public SimpMessagingTemplate template;
@MessageMapping("/subscribe")
public void subscribe(ReceiveMessage rm) {
for(int i =1;i<=20;i++) {
//⼴播使⽤convertAndSend⽅法,第⼀个参数为⽬的地,和js中订阅的⽬的地要⼀致
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
@MessageMapping("/queue")
public void queuw(ReceiveMessage rm) {
System.out.println("进⼊⽅法");
for(int i =1;i<=20;i++) {
/*⼴播使⽤convertAndSendToUser⽅法,第⼀个参数为⽤户id,此时js中的订阅地址为
"/user/" + ⽤户Id + "/message",其中"/user"是固定的*/
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
  6、在src/main/resource包下建⼀个static包,引⼊jquery-3.2.1.min.js、sock.js、stomp.js,创建topic.html和queue.html。<html>
<head>
<meta charset="UTF-8">
<title>Hello topic</title>
<script src="sock.js"></script>
<script src="stomp.js"></script>
<script src="jquery-3.2.1.min.js"></script>
<script type="text/javascript">
var stompClient = null;
function setConnected(connected){
$("#response").html();
}
function connect() {
var socket = new SockJS("/webServer");
stompClient = Stomp.over(socket);
setConnected(true);
console.log('Connected: ' + frame);
stompClient.subscribe('/topic/getResponse', function(response){
var response1 = ElementById('response');
var p = ateElement('p');
p.style.wordWrap = 'break-word';
p.ateTextNode(response.body));
response1.appendChild(p);
});
});
}
function disconnect() {
if (stompClient != null) {
stompClient.disconnect();
}
setConnected(false);
console.log("Disconnected");
}
function sendName() {
var name = ElementById('name').value;
console.info(1111111111);
stompClient.send("/subscribe", {}, JSON.stringify({ 'name': name }));
}
</script>
</head>
<body onload="disconnect()">
<noscript><h2 >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>
<html>
<head>
<meta charset="UTF-8">
<title>Hello queue</title>
<script src="sock.js"></script>
<script src="stomp.js"></script>
<script src="jquery-3.2.1.min.js"></script>
<script type="text/javascript">
var stompClient = null;
function setConnected(connected){
$("#response").html();
}
function connect() {
var socket = new SockJS("/queueServer");
stompClient = Stomp.over(socket);
setConnected(true);
console.log('Connected: ' + frame);
stompClient.subscribe('/user/'+ElementById('user').value+'/message', function(response){
var response1 = ElementById('response');
var p = ateElement('p');
p.style.wordWrap = 'break-word';
p.ateTextNode(response.body));
response1.appendChild(p);
});
});
}
function disconnect() {
if (stompClient != null) {
stompClient.disconnect();
}
setConnected(false);
console.log("Disconnected");
}
function sendName() {
var name = ElementById('name').value;
console.info(1111111111);
stompClient.send("/queue", {}, JSON.stringify({ 'name': name}));
}
</script>
</head>
<body onload="disconnect()">
<noscript><h2 >Seems your browser doesn't support Javascript! Websocket relies on Javascript being enabled. Please enable    Javascript and reload this page!</h2></noscript>
<div>
<div>
<labal>⽤户</labal><input type="text" id="user" />
<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>
  启动项⽬后,先访问topic.html,如图所⽰
  访问queue.html,⾸先以不同的⽤户名建⽴连接,如图所⽰
  zhangsan窗⼝发送12345后:
  lisi窗⼝发送67890后:
  由此便实现了服务端两种推送消息的⽅式(⼴播和点对点)。

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。