在Java中用WebSockets实现一个聊天室示例:java-chatroom

jopen 11年前

java-chatroom是一个在Java中使用WebSockets实现的简单聊天室示例应用。运行方法:

java -jar dist/JavaWebSockets.jar -p [some free port number]

服务器端代码:

ContextHandler contextHandler = new ContextHandler();  contextHandler.setContextPath("/chat");  contextHandler.setHandler(new WebSocketHandler() {    @Override    public void configure(WebSocketServletFactory factory) {      factory.setCreator(new WebSocketCreator() {        @Override        public Object createWebSocket(UpgradeRequest req, UpgradeResponse resp) {          String query = req.getRequestURI().toString();          if ((query == null) || (query.length() <= 0)) {            try {              resp.sendForbidden("Unspecified query");            } catch (IOException e) {              }            return null;          }          return new ChatroomSocket();        }      });    }  });

项目主页:http://www.open-open.com/lib/view/home/1391740500582