如何在 Jetty 中指定 WebSocketServlet 的 URL?
我已阅读 使用 Jetty 创建 WebSocket 聊天应用程序,我想在 Jetty 上使用 WebSocketServlet
创建一个简单的 echo websocket。
我已经像这样创建了我的 WebSocketServlet
:
public class ChatSocketServlet extends WebSocketServlet {
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
PrintWriter out = response.getWriter();
out.println("<!DOCTYPE html><html><body><h1>Chat</h1></body></html>");
}
@Override
public WebSocket doWebSocketConnect(HttpServletRequest request, String protocol) {
return new ChatWebSocket();
}
class ChatWebSocket implements OnTextMessage {
private Connection connection;
@Override
public void onClose(int closeCode, String message) {
System.out.println("onClose");
}
@Override
public void onOpen(Connection connection) {
this.connection = connection;
}
@Override
public void onMessage(String data) {
try {
connection.sendMessage(data);
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
但是我应该使用什么 URL 来连接到这个 websocket?看来我不能像使用 HttpServlet
那样使用 @WebServlet
(例如 @WebServlet("/HelloServlet")
)。我尝试连接到:
ws://localhost:8080/MyJavaWeb/ChatWebSocket
但它返回 Not Found
。是否有其他注释来指定 WebSocketServlet
的 URL?我也不知道从该 servlet 上的 doGet
获取输出的 URL。
I have read Creating a WebSocket-Chat-Application with Jetty and I would like to create a simple echo websocket using a WebSocketServlet
on Jetty.
I have created my WebSocketServlet
like this:
public class ChatSocketServlet extends WebSocketServlet {
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
PrintWriter out = response.getWriter();
out.println("<!DOCTYPE html><html><body><h1>Chat</h1></body></html>");
}
@Override
public WebSocket doWebSocketConnect(HttpServletRequest request, String protocol) {
return new ChatWebSocket();
}
class ChatWebSocket implements OnTextMessage {
private Connection connection;
@Override
public void onClose(int closeCode, String message) {
System.out.println("onClose");
}
@Override
public void onOpen(Connection connection) {
this.connection = connection;
}
@Override
public void onMessage(String data) {
try {
connection.sendMessage(data);
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
But what URL should I use to connect to this websocket? It seems that I can't use the @WebServlet
(e.g. @WebServlet("/HelloServlet")
) as I can with HttpServlet
. I have tried to connect to:
ws://localhost:8080/MyJavaWeb/ChatWebSocket
but it returns Not Found
. Is there any other annotation to specify the URLs for WebSocketServlet
? And I don't know the URL for getting the output from doGet
on this servlet either.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论