我正在尝试在 tomcat 7.0.29 上使用 websocket 来实现 pub/sub 系统,但不知何故我不知道为什么,每次打开浏览器时它总是提醒“关闭”.. env 是 tomcat-7.0。 29,Eclipse Juno,用 scala 编写。如果有人可以提供帮助,非常感谢...
我的servlet如下:
[PubServlet]:
class PubServlet extends WebSocketServlet {
override def createWebSocketInbound (subProtocol: String, request: HttpServletRequest): StreamInbound = {
println("create#############################################")
new WebSocketHandler()
}
}
[初始化服务程序]:
public class InitServlet extends HttpServlet {
private static final long serialVersionUID = -3163557381361759907L;
private static List<MessageInbound> socketList;
public void init(ServletConfig config) throws ServletException {
InitServlet.socketList = new ArrayList<MessageInbound>();
super.init(config);
System.out.println("Server start============");
}
public static synchronized List<MessageInbound> getSocketList() {
return InitServlet.socketList;
}
}
[Websocket处理程序]:
class WebSocketHandler extends MessageInbound{
protected override def onBinaryMessage(arg0: ByteBuffer) {
// TODO Auto-generated method stub
}
protected override def onTextMessage(msg: CharBuffer) {
}
protected override def onClose(status: Int) {
println(status)
super.onClose(status)
}
protected override def onOpen(outbound: WsOutbound) {
super.onOpen(outbound)
InitServlet.getSocketList().add(this)
}
}
我的客户代码在这里:
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Index</title>
<script type="text/javascript">
var ws = null;
function startWebSocket() {
if ('WebSocket' in window){
ws = new WebSocket("ws://localhost:8080/PubSub_Web/index.do");
alert(ws);
}
else if ('MozWebSocket' in window)
ws = new MozWebSocket("ws://localhost:8080/PubSub_Web/index.do");
else
alert("not support");
ws.onmessage = function(evt) {
alert(evt.data);
};
ws.onclose = function(evt) {
alert("close");
};
ws.onopen = function(evt) {
alert("open");
};
}
function sendMsg() {
ws.send(document.getElementById('writeMsg').value);
}
</script>
</head>
<body onload="startWebSocket();">
<input type="text" id="writeMsg"></input>
<input type="button" value="send" onclick="sendMsg()"></input>
</body>
</html>