jetty 既实现了 jsr-356 中定义的 websocket 规范(javax.websocket),也实现了一套自己的 websocket,包名分别是 org.eclipse.jetty.websocket.api 和 org.eclipse.jetty.websocket.jsr356。
为了代码的可移植性,这里采用 javax.websocket。
实现 websocket 处理类
定义一个 websocket 处理类非常简单,只需要在 POJO 上添加一些注解即可:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30
| import javax.websocket.*; import javax.websocket.server.ServerEndpoint; import java.io.IOException;
@ServerEndpoint("/chat") public class ChatWebSocket { @OnOpen public void onOpen(Session session) throws IOException { System.out.println("WebSocket opened: " + session.getId()); }
@OnMessage public void onTextMessage(String message, Session session) { System.out.println("receive text message : " + message); }
@OnError public void onError(Session session, Throwable throwable) { System.out.println("Error happened."); }
@OnClose public void onClose(CloseReason reason, Session session) { System.out.println("Websocket clsoed: " + reason.getReasonPhrase()); } }
|
用 @ServerEndpoint 注解的 POJO 就是一个 websocket 处理类。servlet 容器启动时会自动加载这些类。@ServerEndpoint 可以包含一个路径参数,这个路径下的所有 websocket 连接都会交给这个类来处理。@OnOpen,@OnMessage,@OnError,@OnClose 都是 websocket 不同事件发生时的回调函数。从字面意思很容易判断其含义。
Chatroom source code
1 2 3
| git clone git@github.com:irgb/websocket-chatroom-demo.git git checkout v1.0 mvn jetty:run
|
在浏览器中打开 http://localhost:8080 即可打开聊天界面,打开多个窗口,即可实现聊天:

Reference