简单的 websocket 和静态文件示例
Posted
技术标签:
【中文标题】简单的 websocket 和静态文件示例【英文标题】:Simple websocket and static file example 【发布时间】:2014-08-29 23:17:24 【问题描述】:尝试设置 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());
【问题讨论】:
【参考方案1】:下面解决它
Undertow.builder()
.addHttpListener(8000,"localhost")
.setHandler(path()
.addPrefixPath("/", resource(new ClassPathResourceManager(main.class.getClassLoader(), main.class.getPackage())).addWelcomeFiles("WSGSS/index.html"))
.addPrefixPath("/websocket",manager.deployment()))
.build()
.start();
【讨论】:
以上是关于简单的 websocket 和静态文件示例的主要内容,如果未能解决你的问题,请参考以下文章
gcc生成静态链接库与动态链接库步骤,并链接生成可执行文件的简单示例
SpringBoot——SpringBoot集成WebSocket实现简单的多人聊天室
SpringBoot——SpringBoot集成WebSocket实现简单的多人聊天室