基于Jetty8的WebSocket聊天Demo

 

基于Jetty8的WebSocket聊天Demo

先上代码

ChatWebSocketServlet

@WebServlet("/ws/jetty")
public class ChatWebSocketServlet extends WebSocketServlet {

    private static final long serialVersionUID = 911879078000755859L;

    private final Set _members = new CopyOnWriteArraySet();

    class MyWebSocket implements OnTextMessage {
        private String userName = "匿名用户";

        public MyWebSocket(String userName) {
            if (userName != null && userName.length() > 0) {
                this.userName = userName;
            }
        }

        private Connection conn;

        @Override
        public void onOpen(Connection connection) {
            System.out.println("onOpen" + connection.isOpen());
            this.conn = connection;
            _members.add(this);

        }

        @Override
        public void onClose(int closeCode, String message) {
            System.out.printf("onClose %s %s \t", closeCode, message);
            _members.remove(this);

        }

        @Override
        public void onMessage(String data) {
            for (MyWebSocket s : _members) {
                try {
                    if (s.conn.isOpen())
                        s.conn.sendMessage(data);
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }

        }
    }

    public WebSocket doWebSocketConnect(HttpServletRequest request, String protocol) {
        // TODO Auto-generated method stub
        String name = request.getParameter("username");
        System.out.println(name + "is connected protocol=" + protocol);
        return new MyWebSocket(name);
    }

    @Override
    protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException,
            IOException {
        // TODO Auto-generated method stub
        super.service(request, response);
    }

}

 

 

html 页面


    WebSocket Chat
    
    

Username: 

This is a demonstration of the Jetty websocket server.

 

 

  jetty 下载地址

http://dist.codehaus.org/jetty/jetty-hightide-8.1.0/jetty-hightide-8.1.0.RC5.tar.gz

 

启动jetty(注:jetty8.1 启动后jsp编译报错,加参数-Dorg.apache.jasper.compiler.disablejsr199=true 可以解决)

java -jar start.jar jetty.port=8088 -Dorg.apache.jasper.compiler.disablejsr199=true

 

项目打成war 包放 jetty.home 的webapps 目录即可。

 

参考链接

 http://blog.csdn.net/lixinso/article/details/6525874
 

http://blog.csdn.net/suixiang888/article/details/9959993

 

 

你可能感兴趣的:(java)