WebSocket聊天室v2.0

在原WebSocket聊天室的基础上,增加了显示当前信息是谁发出的、实现了退出当前会话功能和对界面进行了简单的优化。
待解决部分:登陆时由客户端向服务器传userName的时候中文会出现乱码。

客户端池代码:

package cn.com.demo.websocket.servlet;

import java.io.IOException;
import java.nio.CharBuffer;
import java.util.HashSet;
import java.util.Map;
import java.util.Hashtable;
import java.util.Set;


public class ClientPools {
    private static Set clients = new HashSet();
    private static Map clientsMap = new Hashtable();
    public static void addClient(MyMessageInbound client)
    {
        clients.add(client);
    }
    
    public static void addClient(String userName,MyMessageInbound client)
    {
        clientsMap.put(userName,client);
    }
    
    public static Set getAllUserName()
    {
        return clientsMap.keySet();
    }
    public static void removeClient(MyMessageInbound client)
    {
        clientsMap.remove(client.getName());
        System.out.println(client.getName()+"成功退出!");
    }
    
    public static void sendLoginMessage(String message)
    {
        
    }
    
    public static void sendMessage(String message)
    {
        for(String key:clientsMap.keySet())
        {
            try {
                //给client发送消息
                clientsMap.get(key).getWsOutbound().writeTextMessage(CharBuffer.wrap(message));
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    }
}

MyMessageInbound代码,其中对onClose()进行了重写,增加了向客户端发送退出后的当前用户列表和显示XX退出了

package cn.com.demo.websocket.servlet;

import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.CharBuffer;
import java.util.Set;

import org.apache.catalina.websocket.MessageInbound;
import org.apache.catalina.websocket.WsOutbound;

public class MyMessageInbound extends MessageInbound {
    private String name;
    public MyMessageInbound(String name){
        this.name = name;
    }
    public String getName()
    {
        return this.name;
    }
    @Override
    protected void onClose(int status) {
        ClientPools.removeClient(this);
        ClientPools.sendMessage(this.name+"离开了!");
        Set userNames = ClientPools.getAllUserName();
        String str ="{type:'userList',value:[";
        if(userNames!=null)
        {
            for(String name:userNames)
            {
                str = str+"'"+name+"',";
            }
        }
        str = str + "]}";
        ClientPools.sendMessage(str);
        System.out.println("用户退出");
    }

    @Override
    protected void onOpen(WsOutbound outbound) {
        ClientPools.addClient(this);
        ClientPools.sendMessage(this.name+"上线了!");
        Set userNames = ClientPools.getAllUserName();
        String str ="{type:'userList',value:[";
        if(userNames!=null)
        {
            for(String name:userNames)
            {
                str = str+"'"+name+"',";
            }
        }
        str = str + "]}";
        ClientPools.sendMessage(str);
    }

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

    }

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

}

MyMessageServlet代码,由于要匹配当前用户名,所以在原来的基础上从客户端获取了userName:

package cn.com.demo.websocket.servlet;

import java.io.IOException;
import java.io.UnsupportedEncodingException;

import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.catalina.websocket.StreamInbound;
import org.apache.catalina.websocket.WebSocketServlet;

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

    @Override
    protected StreamInbound createWebSocketInbound(String arg0,
            HttpServletRequest arg1) { 
        String userName = arg1.getParameter("userName");
        MyMessageInbound inbound = new MyMessageInbound(userName);
        System.out.println(inbound.hashCode());
        ClientPools.addClient(userName,inbound);
        return inbound;
    }

}

客户端代码,其中退出后清空标签内容由于没有使用jQuery,所以直接用document.getElementById("Layer1").innerHTML="";进行清空,有内存泄漏的风险。










你可能感兴趣的:(WebSocket聊天室v2.0)