我正在使用gwt-web-sockets-1.0.0.jar在我的电脑上的GWT示例中实现一个简单的websocket。 我在各种浏览器中尝试过,在所有浏览器中我都看到了错误或关闭处理程序。
这是我的代码:
public class WebSocketView extends Composite{
private WebSocket webSocket;
private TextBox url;
private TextBox input;
private Button connect;
private Button disconnect;
...
url = new TextBox();
url.setValue("ws://127.0.0.1:8080/sample/websocket/Test");
input = new TextBox();
input.setValue("Hello World!");
connect = new Button("Connect", new ClickHandler() {
@Override
public void onClick(ClickEvent event) {
connect();
}
});
disconnect = new Button("Disconnect", new ClickHandler() {
@Override
public void onClick(ClickEvent event) {
webSocket.close();
}
});
send = new Button("Send", new ClickHandler() {
@Override
public void onClick(ClickEvent event) {
webSocket.send(input.getValue());
}
});
...
public void connect() {
try {
webSocket = create(url.getValue());
webSocket.setOnOpen(new OpenHandler() {
@Override
public void onOpen(WebSocket webSocket) {
GWT.log("opened successfully");
}
});
webSocket.setOnClose(new CloseHandler() {
@Override
public void onClose(WebSocket webSocket) {
GWT.log("closed");
}
});
webSocket.setOnError(new ErrorHandler() {
@Override
public void onError(WebSocket webSocket) {
GWT.log("error");
}
});
webSocket.setOnMessage(new MessageHandler() {
@Override
public void onMessage(WebSocket webSocket, MessageEvent event) {
GWT.log("having message");
}
});
} catch (JavaScriptException e) {
output(e.toString(), "red");
}
}
public static native WebSocket create(String url) /*-{
return new WebSocket(url);
}-*/;
}
web.xml servlet定义:
<servlet>
<servlet-name>myWebSocket</servlet-name>
<servlet-class>ir.myCompany.sample.server.websocket.MyWebSocketServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>myWebSocket</servlet-name>
<url-pattern>/sample/websocket/Test</url-pattern>
</servlet-mapping>
服务器端代码:
public class MyWebSocketServlet extends WebSocketServlet {
private static final long serialVersionUID = 1L;
ChatMessageInbound chatMessageInbound = new ChatMessageInbound();
public MyWebSocketServlet() {
System.out.println("constructor called!");
}
@Override
protected StreamInbound createWebSocketInbound(String arg0, HttpServletRequest arg1) {
System.out.println(arg0);
return chatMessageInbound;
}
}