WebSocket实现“多人”简单聊天室

话不多说,直接上代码。。。

1.java后台代码

package www.test;

import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.CharBuffer;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
 
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
 
import org.apache.catalina.websocket.MessageInbound;
import org.apache.catalina.websocket.StreamInbound;
import org.apache.catalina.websocket.WebSocketServlet;
import org.apache.catalina.websocket.WsOutbound;
 
@WebServlet("/chat")
public class ChatWebSocketServlet extends WebSocketServlet {
    private final Map map = new HashMap();
    private static final long serialVersionUID = -1058445282919079067L;
    @Override
    protected StreamInbound createWebSocketInbound(String arg0, HttpServletRequest request) {
        // StreamInbound:基于流的WebSocket实现类(带内流),应用程序应当扩展这个类并实现其抽象方法onBinaryData和onTextData。
        return new ChatMessageInbound();
    }
    class ChatMessageInbound extends MessageInbound {
        // MessageInbound:基于消息的WebSocket实现类(带内消息),应用程序应当扩展这个类并实现其抽象方法onBinaryMessage和onTextMessage。
        @Override
        protected void onOpen(WsOutbound outbound) {
            map.put(outbound.hashCode(), outbound);
            super.onOpen(outbound);
        }
        @Override
        protected void onClose(int status) {
            map.remove(getWsOutbound().hashCode());
            super.onClose(status);
        }
        @Override
        protected void onBinaryMessage(ByteBuffer buffer) throws IOException {
        }
        @Override
        protected void onTextMessage(CharBuffer buffer) throws IOException {
            String msg = buffer.toString();
            Date date = new Date();
            SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss.SSS");
            msg = " 匿名用戶  " + sdf.format(date) + "
" + msg; broadcast(msg); } private void broadcast(String msg) { Set set = map.keySet(); for (Integer integer : set) { WsOutbound outbound = map.get(integer); CharBuffer buffer = CharBuffer.wrap(msg); try { outbound.writeTextMessage(buffer); outbound.flush(); } catch (IOException e) { e.printStackTrace(); } } } } }

2.html和js代码





多人聊天室


	 

欢迎来到聊天室

3.效果图

WebSocket实现“多人”简单聊天室_第1张图片

你可能感兴趣的:(java,javascript)