我需要在Java SE中实现一个相当简单的WebSocket服务器。它所需要做的就是接受连接并存储相应的会话,然后在触发某个事件时向所有连接的客户端发送消息。
我找不到一个关于如何在普通Java SE中实现这一点的教程。所有这些都需要使用Maven运行,或者将其部署为WAR -这对于这个项目来说都是不可能的。我需要将其作为Java SE桌面应用程序运行。
我找到的教程展示了如何使用@OnOpen
,@OnMessage
和@OnClose
等注解实现端点。然而,它们都没有解释如何实际初始化服务器。我还需要能够为传入连接指定不同的端口号。
我错过了什么吗?我知道人们已经用WebSocket开发了聊天应用程序,这真的不需要Web应用程序服务器。我也没有使用Maven,为了简单起见,我宁愿保持这种方式。
4条答案
按热度按时间bweufnob1#
https://github.com/TooTallNate/Java-WebSocket是Java SE中的完整WebSockets服务器和客户端实现,不需要企业/Web应用服务器。
68de4m5k2#
Java 11服务器代码:
字符串
pom.xml:
型
JavaScript客户端:
型
vfhzx4xs3#
尝试使用Stefan的代码。目前它不能很好地工作(我使用Firefox)。大于1024字节的WebSocket数据包被分割成TCP段,因此需要重新组装。下面是阅读浏览器数据包的更新代码:
字符串
hujrc8aj4#
字符串
这修复了Stefan的答案的问题。它可以在一次读取中处理多个消息,也可以在一次读取中处理多个消息。还修复了在写入中使用int而不是long的问题。