我想通过websocket与服务器通信,但现在的问题是每次我尝试使用var connection = new WebSocket('ws://localhost:8080/WebsocketHome/actions');
建立连接时,它显示“ WebSocket握手期间出错:意外的响应代码:404”错误。我正在使用jboss v4.0服务器。我正在使用的jar文件是“ jboss-websocket-api_1.1_spec-1.1.3.Final.jar”。我很可能尝试了stackoverflow上提供的所有解决方案
下面是代码DeviceWebSocketServer.java
package websocket;
import java.io.IOException;
import javax.websocket.OnClose;
import javax.websocket.OnError;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.ServerEndpoint;
@ServerEndpoint("/actions")
public class DeviceWebSocketServer
{
@OnOpen
public void onOpen(Session session) {
System.out.println("onOpen::" + session.getId());
}
@OnClose
public void onClose(Session session) {
System.out.println("onClose::" + session.getId());
}
@OnMessage
public void onMessage(String message, Session session) {
System.out.println("onMessage::From=" + session.getId() + " Message=" + message);
try {
session.getBasicRemote().sendText("Hello Client " + session.getId() + "!");
} catch (IOException e) {
e.printStackTrace();
}
}
@OnError
public void onError(Throwable t) {
System.out.println("onError::" + t.getMessage());
}
}
web.xml文件
<?xml version="1.0" encoding="UTF-8"?>
<web-app id="WebApp_ID" version="2.4" xmlns="http://java.sun.com/xml/ns/j2ee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
<display-name>WebsocketHome</display-name>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
<welcome-file>index.htm</welcome-file>
<welcome-file>index.jsp</welcome-file>
<welcome-file>default.html</welcome-file>
<welcome-file>default.htm</welcome-file>
<welcome-file>default.jsp</welcome-file>
</welcome-file-list>
</web-app>
下面是项目结构