nutzwk4.0项目中引用nutz-websokcet,在pom中引入了两个依赖,
浏览器端
// 首先,需要创建一个WebSocket连接
var ws;
var WS_URL = window.location.host + "${base!}"+"/websocket"
// 如果页面是https,那么必须走wss协议, 否则走ws协议
if (location.protocol == 'http:') {
ws = new WebSocket("ws://"+WS_URL);
} else {
ws = new WebSocket("wss://"+WS_URL);
}
// 连接成功后,会触发onopen回调
ws.onopen = function(event) {
console.log("websocket onopen ...");
// 加入home房间
ws.send(JSON.stringify({room:'home',"action":"join"}));
};
// 收到服务器发来的信息时触发的回调
ws.onmessage = function(event) {
console.log("websocket onmessage", event.data);
var re = JSON.parse(event.data);
if (re.action == "notify") {
// 弹个浏览器通知
} else if (re.action == "msg") {
// 插入到聊天记录中
}
};
ws.onclose = function(evt) {
console.log("Connection closed.");
};
// 定时发个空消息,避免服务器断开连接
function ws_ping() {
if (ws) {
ws.send("{}"); // TODO 断线重连.
}
}
setInterval("ws_ping()", 25000); // 25秒一次就可以了
后台
@ServerEndpoint(value = "/websocket", configurator=NutWsConfigurator.class)
@IocBean // 使用NutWsConfigurator的必备条件
public class GybWebsocket extends AbstractWsEndpoint {
// 并不需要你马上实现任何方法,它也马上能工作
}
浏览器console,也没有报错,就是连接了之后立刻断开。
websocket onopen ...
Connection closed.
WebSocket is already in CLOSING or CLOSED state.
debug了一下:
在AbstractWsEndpoint,貌似除了一些问题
public void onOpen(Session session, EndpointConfig config) {
this.changeSessionId(session);
String wsid = session.getId();
WsHandler handler = this.createHandler(session, config);
handler.setRoomProvider(this.roomProvider);
handler.setSession(session);
handler.setHttpSession((HttpSession)config.getUserProperties().get("HttpSession"));
handler.setEndpoint(this);
handler.init();
session.addMessageHandler(handler);
this.sessions.put(wsid, session); //断点无法运行到这里...
this.handlers.put(wsid, handler);
}
日志:websocket就只有这一句
[DEBUG] 2018-01-06 17:49:45,370 org.nutz.mvc.impl.UrlMappingImpl.get(UrlMappingImpl.java:110) - Search mapping for [GET] path=/websocket : NOT Action match
[DEBUG] 2018-01-06 17:49:45,374 org.nutz.ioc.impl.NutIoc.get(NutIoc.java:157) - Get 'gybWebsocket'<class cn.wizzer.app.web.commons.websocket.GybWebsocket>
然后我试了一下原生的websocketapi,没毛病...
@ServerEndpoint(value = "/websocket1")
public class TestWs {
@OnOpen
public void onOpen(Session session, EndpointConfig config) {
System.out.print(1);
}
@OnClose
public void onClose(Session session, CloseReason closeReason) {
}
}
希望大佬能指点一下~,谢谢