Wildfly 11中WebSocket客户端URI及端点部署问题咨询
嘿,我来帮你搞定WildFly 11上的WebSocket端点部署和连接URI问题!
部署WebSocket端点到WildFly 11
WildFly 11原生支持JSR-356(Java WebSocket规范),不需要额外添加依赖,只要你的代码符合规范就能直接部署。
1. 编写你的WebSocket端点
有两种常用方式实现端点,选你习惯的就行:
注解式(推荐)
直接用@ServerEndpoint注解标记你的端点类,这个注解里的路径就是你提到的url部分:
import javax.websocket.OnMessage; import javax.websocket.OnOpen; import javax.websocket.Session; import javax.websocket.server.ServerEndpoint; @ServerEndpoint("/my-websocket") // 这里的路径就是端点的url,记好它! public class MyWebSocketEndpoint { @OnOpen public void onClientConnect(Session session) { System.out.println("新客户端连接: " + session.getId()); } @OnMessage public String handleMessage(String clientMessage) { return "服务器收到: " + clientMessage; } }
web.xml配置式(可选)
如果不想用注解,也可以在WEB-INF/web.xml里显式配置端点:
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" version="3.1"> <websocket-endpoint> <endpoint-class>com.yourpackage.MyWebSocketEndpoint</endpoint-class> <url-pattern>/my-websocket</url-pattern> </websocket-endpoint> </web-app>
2. 打包成WAR文件
把你的Java类、web.xml(如果用了)等资源打包成标准的WAR文件。比如你的项目叫websocket-app,打包后就是websocket-app.war。
3. 部署到WildFly 11
WildFly提供了多种部署方式,挑你方便的用:
- 管理控制台部署:打开浏览器访问
http://localhost:9990(你已经知道的管理地址),登录后进入「Deployments」页面,点击「Add」上传你的WAR文件,然后启用部署即可。 - 手动复制部署:找到WildFly安装目录下的
standalone/deployments文件夹,直接把WAR文件复制进去,WildFly会自动检测并完成部署。 - CLI命令部署:打开WildFly的CLI工具(
bin/jboss-cli.sh或bin/jboss-cli.bat),连接服务器后执行命令:deploy /本地路径/websocket-app.war
确定最终的WebSocket连接URI
现在部署完成了,按照ws://hostname:port/context-root/endpoint-url的格式拼接就行,我给你逐个拆解:
- hostname:本地测试就是
localhost - port:注意!你提到的
9990是WildFly的管理端口,应用访问的默认HTTP端口是8080,所以这里要用8080 - context-root:默认是你的WAR文件名(不带
.war后缀),比如websocket-app;如果想自定义,可以在WEB-INF/jboss-web.xml里设置:<jboss-web> <context-root>/my-custom-app</context-root> </jboss-web> - endpoint-url:就是你在
@ServerEndpoint或web.xml里配置的路径,比如/my-websocket
举个实际例子:如果你的WAR是websocket-app.war,端点路径是/my-websocket,那最终的URI就是:ws://localhost:8080/websocket-app/my-websocket
快速测试连接
你可以用一个简单的HTML页面测试连接是否正常:
<!DOCTYPE html> <html> <head> <title>WebSocket测试</title> </head> <body> <input type="text" id="msgInput" placeholder="输入消息"> <button onclick="sendMsg()">发送</button> <div id="responseArea"></div> <script> const ws = new WebSocket('ws://localhost:8080/websocket-app/my-websocket'); ws.onopen = () => { document.getElementById('responseArea').innerHTML += "✅ 连接成功!<br>"; }; ws.onmessage = (event) => { document.getElementById('responseArea').innerHTML += "📥 服务器响应: " + event.data + "<br>"; }; function sendMsg() { const msg = document.getElementById('msgInput').value; ws.send(msg); document.getElementById('msgInput').value = ""; } </script> </body> </html>
打开这个页面,输入消息点击发送,就能看到连接状态和消息交互了。
内容的提问来源于stack exchange,提问作者Johannes Gnadlinger
相关产品推荐
相关产品推荐

