我使用Javascript客户端在Java中创建了一个简单的聊天服务器,但是我在接收从JavaScript到Java的消息时遇到了问题。
当我使用Java客户端时,它工作正常,但是当我使用Javascript时,我遇到了问题。
我的代码:
爪哇
public class ChatRunner {
public static void main(String[] args) throws Exception {
Server server = new Server();
ServerConnector connector = new ServerConnector(server);
connector.setPort(8080);
server.addConnector(connector);
ServletContextHandler context = new ServletContextHandler(
ServletContextHandler.SESSIONS);
context.setContextPath("/");
server.setHandler(context);
try {
ServerContainer wscontainer = WebSocketServerContainerInitializer
.configureContext(context);
wscontainer.addEndpoint(ChatEndpoint.class);
server.start();
server.dump(System.err);
server.join();
} catch (Throwable t) {
t.printStackTrace(System.err);
}
}
}
@ServerEndpoint(value="/events/")
public class ChatEndpoint {
@OnOpen
public void onWebSocketConnect(Session sess) {
System.out.println("Socket Connected: " + sess);
}
@OnMessage
public void onWebSocketText(String message) {
System.out.println("Received TEXT message: " + message);
}
@OnClose
public void onWebSocketClose(CloseReason reason) {
System.out.println("Socket Closed: " + reason);
}
@OnError
public void onWebSocketError(Throwable cause) {
cause.printStackTrace(System.err);
}
}
JavaScript的:
var ws = new WebSocket("ws://localhost:8080/events/");
ws.onopen = function() { ws.send("Hello"); };