有一个项目,比如聊天室。
1,在我的测试html5页面(使用sockjs stomp.js)为什么在连接成功约3分钟后连接丢失了?
2,我应该实施与心跳相关的任何代码吗?
3,Android使用 StomprotocolAndroid (https://github.com/NaikSoftware/StompProtocolAndroid)和iOS使用 WebsocketStompKit (https://github.com/mykoma/WebsocketStompKit)也会在几分钟后断开连接。
4,另一个项目,使用类似的代码,但服务器端将“h”发送给客户端 并且html5页面什么都不做,它仍然可以保持连接?
测试结果
12:12:30打开网络插座...
12:12:31网络套接字打开......
12:12:31>>> CONNECT accept-version:1.1,1.0心跳:10000,10000
12:12:32<<<连接版本:1.1心跳:0,0
12:12:32连接到服务器undefined
12:12:32>>> SUBSCRIBE id:sub-0 destination:/ topic / greetings
12:12:32>>> SUBSCRIBE id:sub-1 destination:/ user / 2 / message
12:15:32哎呀!失去与http://xxxxxx.org/hello
的连接
服务器端
配置代码:
@Configuration
@EnableWebSocketMessageBroker
public class WebSocketConfig extends AbstractWebSocketMessageBrokerConfigurer {
public void registerStompEndpoints(
StompEndpointRegistry stompEndpointRegistry) {
stompEndpointRegistry.addEndpoint("/hello").setAllowedOrigins("*")
.withSockJS();
}
@Override
public void configureMessageBroker(MessageBrokerRegistry registry) {
registry.enableSimpleBroker("/topic", "/user");
registry.setApplicationDestinationPrefixes("/app");
registry.setUserDestinationPrefix("/user");
}
}
控制器代码:
/***/
@RestController
public class GreetingController {
@Autowired
private SimpMessageSendingOperations simpMessageSendingOperations;
@MessageMapping("/hello")
@SendTo("/topic/greetings")
public Greeting greeting(@Header("atytopic") String topic, @Headers Map<String, Object> headers) {
System.out.println("connected successfully....");
System.out.println(topic);
System.out.println(headers);
return new Greeting("return from /topic/greetings");
}
@MessageMapping("/message")
@SendToUser("/message")
public Greeting handleSubscribe() {
System.out.println("this is the @SubscribeMapping('/marco')");
return new Greeting("I am a msg from SubscribeMapping('/macro').");
}
@RequestMapping(path = "/send", method = RequestMethod.GET)
public Greeting send() {
simpMessageSendingOperations.convertAndSendToUser("1", "/message", new Greeting("I am a msg from SubscribeMapping('/macro')."));
return new Greeting("I am a msg from SubscribeMapping('/macro').");
}
}
客户端
JSP测试页面代码:
<%@ 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/3.1.1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
//connect();
});
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 = '';
}
//this line.
function connect() {
var userid = document.getElementById('name').value;
var socket = new SockJS("http://xxxxx.org/hello");
stompClient = Stomp.over(socket);
stompClient.debug = function(str) {
// append the debug log to a #debug div somewhere in the page using JQuery:
$("#debug").append(getNowFormatDate() + ":" + str + "<br/>");
};
stompClient.connect({}, function(frame) {
setConnected(true);
console.log('Connected: ' + frame);
stompClient.subscribe('/topic/greetings', function(greeting){
showGreeting(JSON.parse(greeting.body).content);
});
stompClient.subscribe('/user/' + userid + '/message',function(greeting){
//alert(JSON.parse(greeting.body).content);
showGreeting(JSON.parse(greeting.body).content);
});
},function (error) {
//errorCallBack
console.log('【' + error + '】');
}
);
}
function sendName() {
var name = document.getElementById('name').value;
stompClient.send("/app/hello", {atytopic:"greetings"}, JSON.stringify({ 'name': name }));
}
function connectAny() {
var socket = new SockJS("http://xxxxxxx.org/hello");
stompClient = Stomp.over(socket);
stompClient.connect({}, function(frame) {
setConnected(true);
console.log('Connected: ' + frame);
stompClient.subscribe('/topic/feed', function(greeting){
alert(JSON.parse(greeting.body).content);
showGreeting(JSON.parse(greeting.body).content);
});
});
}
function disconnect() {
if (stompClient != null) {
stompClient.disconnect();
}
setConnected(false);
console.log("Disconnected");
}
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);
}
function getNowFormatDate() {
var date = new Date();
var seperator1 = "-";
var seperator2 = ":";
var month = date.getMonth() + 1;
var strDate = date.getDate();
if (month >= 1 && month <= 9) {
month = "0" + month;
}
if (strDate >= 0 && strDate <= 9) {
strDate = "0" + strDate;
}
var currentdate = date.getFullYear() + seperator1 + month + seperator1 + strDate
+ " " + date.getHours() + seperator2 + date.getMinutes()
+ seperator2 + date.getSeconds();
return currentdate;
}
</script>
</head>
<body>
<div>
<button id="connect" onclick="connect();">Connect</button>
<button id="connectAny" onclick="connectAny();">ConnectAny</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>
<br/>
<hr>
<div id="debug"></div>
</div>
</body>
</html>