麻烦各位大神给看一下
环境: JDK1.7
resin 4.0.37
浏览器端:
<script>
// 首先,需要创建一个WebSocket连接
var websocketC;
// 如果页面是https,那么必须走wss协议, 否则走ws协议
var wss = "ws://localhost/webscoket";
websocketC = new WebSocket(wss);
// 连接成功后,会触发onopen回调
websocketC.onopen = function(event) {
console.log("websocket onopen ...");
// 加入home房间
websocketC.send(JSON.stringify({"action":"sayhi", "nickname" : "wendal"}));
};
// 收到服务器发来的信息时触发的回调
websocketC.onmessage = function(event) {
console.log("websocket onmessage", event.data);
var re = JSON.parse(event.data);
if (re.action == "notify") {
// 弹个浏览器通知
} else if (re.action == "msg") {
// 插入到聊天记录中
}
};
// 定时发个空消息,避免服务器断开连接
function ws_ping() {
if (websocketC) {
websocketC.send("{}"); // TODO 断线重连.
}
}
setInterval("ws_ping()", 25000); // 25秒一次就可以了
</script>
服务器端:
@ServerEndpoint(value = "/webscoket", configurator=NutWsConfigurator.class)
@IocBean
public class WebSocket extends AbstractWsEndpoint {
public WsHandler createHandler(Session session, EndpointConfig config) {
return new MySimpleWsHandler(); // 是的,返回你自己的实现类就可以了,需要每次新建哦
}
}
public class MySimpleWsHandler extends SimpleWsHandler{
public MySimpleWsHandler() {
super(""); // 覆盖默认前缀
}
public void sayhi(NutMap req) { // 对应js端的action名称,方法参数必须是NutMap哦
String name = req.getString("name");// 可以拿到页面发过来的任意内容
NutMap resp = new NutMap("action", "join"); // 响应的内容完全由你决定,推荐用{action:"xxx", ....}
resp.setv("msg", "hi ");
endpoint.sendJson(session.getId(), resp); // 通过endpoint可以发生给任何你想发生的对象, session就是当前WebSocket的会话.
}
}
服务器端 主模块:
@Modules(scanPackage=true)
@IocBy(type = ComboIocProvider.class, args = {"*js", "ioc/","*anno","cn"})
@SetupBy(HelloMvcSetup.class)
@Localization("msg")
@Views({GuaguaViewMaker.class})
@Ok("ggjson")
@Fail("errMsg")
public class MainModule {}
浏览器 console 报异常:
WebSocket connection to 'ws://localhost/webscoket' failed: Error during WebSocket handshake: Unexpected response code: 404
2webscoket.html:32 WebSocket is already in CLOSING or CLOSED state.