您可以在下面找到所有代码, 启动了 tomcat 服务器,它运行良好。 但是在发出 websocket 请求时我收到 404 错误。 这是 chrome 控制台中的错误:
WebSocket connection to 'ws://localhost:8088/websocket-example/websocket' failed: Error during WebSocket handshake: Unexpected response code: 404
并且没有服务器日志。
Java WebSocket 代码:WebSocketTest.java
package com.websockets;
import java.io.IOException;
import javax.websocket.OnClose;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.ServerEndpoint;
@ServerEndpoint("/websocket")
public class WebSocketTest {
@OnMessage
public void onMessage(String message, Session session) throws IOException,
InterruptedException {
System.out.println("Message: " + message);
session.getBasicRemote().sendText("Hello Mr. " + message);
}
@OnOpen
public void onOpen() {
System.out.println("Client connected");
}
@OnClose
public void onClose() {
System.out.println("Connection closed");
}
}
JS 代码:hello.html
var webSocket = new WebSocket('ws://localhost:8088/websocket-example/websocket');
网络.xml
<?xml version="1.0" encoding="ISO-8859-1"?>
<web-app
xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
version="3.0">
<welcome-file-list>
<welcome-file>hello.html</welcome-file>
</welcome-file-list>
</web-app>
文件夹结构在tomcat/webapps下..
->webapps
->websocket-example
->hello.html
->WEB-INF
->classes
->com
->websockets
-> WebSocketTest.class
->web.xml
更多信息:
java version "1.7.0_75"
apache-tomcat-8.0.32
server running port : 8088
我不确定这些信息是否足够,让我知道任何其他需要调试的细节吗?
最佳答案
从 $JAVA_HOME/lib 中删除了不需要的 jar。 然后添加 javax.websocket-api-1.0-rc4.jar 然后它工作正常。
关于java - WebSocket 连接到 'ws://*' 失败 : Error during WebSocket handshake: Unexpected response code: 404,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35436379/