试图设置 undertwo 来玩一下,我试图提供一个静态 html 文件 index.html 并添加我注释的 websocket ServerEndpoint pojo 所以我做了以下
final Xnio xnio = Xnio.getInstance("nio", Undertow.class.getClassLoader());
final XnioWorker xnioWorker = xnio.createWorker(OptionMap.builder().getMap());
WebSocketDeploymentInfo webSockets = new WebSocketDeploymentInfo ()
.addEndpoint(Socket.class)
.setWorker(xnioWorker);
final DeploymentManager deployment = defaultContainer()
.addDeployment(deployment()
.setClassLoader(main.class.getClassLoader())
.setContextPath("/websockets")
.setDeploymentName("websockets")
.addServletContextAttribute(WebSocketDeploymentInfo.ATTRIBUTE_NAME, webSockets));
deployment.deploy();
deployment.start();
Undertow.builder()
.addHttpListener(8000,"localhost")
.setHandler(path().addPrefixPath("/", resource(new ClassPathResourceManager(main.class.getClassLoader(), main.class.getPackage())).addWelcomeFiles("WSGSS/index.html")))
.build()
.start();
index.html 得到了预期的服务,但我似乎无法连接到 websocket,而且我确信我在部署 websocket 的方式上做错了,如果我按照 github 上的示例进行操作,它可以工作,但是我找不到提供静态文件的正确方法
在javascript中我得到了异常
var ws = new WebSocket("ws://localhost:8000/websockets/socket")
WebSocket connection to 'ws://localhost:8000/websockets/socket' failed: Error during WebSocket handshake: Unexpected response code: 404
这也是我的 ServerEndpoint
@ServerEndpoint(value = "/socket",
encoders = CommandEncoder.class,
decoders = CommandDecoder.class)
public class Socket{
private static final Set<Session> sessions = Collections.synchronizedSet(new HashSet<Session>());
private final Logger log = Logger.getLogger(getClass().getName());
@OnMessage
public void onMessage(Session session,Command command){
log.info("command of type "+ command.getAction() + " recieved");
command.Process();
try{
session.getBasicRemote().sendObject(command);
//Future<Void> future = session.getAsyncRemote().sendText(message);
} catch (IOException | EncodeException ex){
log.info(ex.getMessage() + ex.getCause());
}
}
@OnOpen
public void onOpen(Session session){
sessions.add(session);
log.info("new session created "+ session.getId());
}
@OnClose
public void onClose(Session session){
sessions.remove(session);
}
@OnError void onError(Session session,Throwable thr){
log.info(session.getId() + " error " + thr.getMessage() + thr.getCause());
}
}