基于WebSocket的网上聊天室

思路:
服务端:
1、创建一个Inbound类,继承MessageInbound(client对象)
2、重写Inbound中的on方法
onOpen()、onClose()、onMessage()
3、创建ClientPools(客户端池)
1)保存所有Client对象(数据结构)
2)添加和移除Client对象
3)给所有Client发送消息的方法
4、创建WebSocketServlet的子类
重写createWebSocketInbound方法,返回第1步所创建的类
5、用注解部署Servlet

客户端Client:
1、创建WebSocket对象("ws://ip:port/上下文/url")
2、给WebSocket对象的
onopen、onclose、onmessage(对象.data)、onerror事件捆绑函数
3、发送按钮,调用webSocket对象的send()发送消息,离开使用close()关闭链接

实现代码:
客户端池ClientPools:

public class ClientPools {
    private static Set clients = new HashSet();
    
    public static void addClient(MyMessageInbound client)
    {
        clients.add(client);
    }
    
    public static void removeClient(MyMessageInbound client)
    {
        clients.remove(client);
    }
    
    public static void sendMessage(String message)
    {
        for(MyMessageInbound client:clients)
        {
            try {
                //给client发送消息
                client.getWsOutbound().writeTextMessage(CharBuffer.wrap(message));
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    }
}

MessageInbound:

public class MyMessageInbound extends MessageInbound {

    @Override
    protected void onClose(int status) {
        ClientPools.removeClient(this);
    }

    @Override
    protected void onOpen(WsOutbound outbound) {
        ClientPools.addClient(this);
        ClientPools.sendMessage("新人上线!");
        System.out.println("新人上线");
    }

    @Override
    protected void onBinaryMessage(ByteBuffer arg0) throws IOException {
        // TODO Auto-generated method stub

    }

    @Override
    protected void onTextMessage(CharBuffer arg0) throws IOException {
        //有消息过来就会触发这个事件,把当前消息,推送给其他client
        System.out.println(arg0.toString());
        ClientPools.sendMessage(arg0.toString());
    }

}

WebSocketServlet:

@WebServlet(urlPatterns = {"/testMsg"})
public class MyMessageServlet extends WebSocketServlet {

    @Override
    protected StreamInbound createWebSocketInbound(String arg0,
            HttpServletRequest arg1) { 
        System.out.println("!!!!!!!!!!!!!");
        return new MyMessageInbound();
    }

}

html页面代码:











你可能感兴趣的:(基于WebSocket的网上聊天室)