欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

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

程序员文章站 2022-05-21 13:49:41
...

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

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<Integer, WsOutbound> map = new HashMap<Integer, WsOutbound>();
    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 = " <font color=green>匿名用戶  " + sdf.format(date) + "</font><br/> " + msg;
            broadcast(msg);
        }
        private void broadcast(String msg) {
            Set<Integer> 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代码

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>多人聊天室</title>
</head>
<body>
	 <h2 align="center">欢迎来到聊天室</h2>
    <div align="center">
        <div id="chat">
            <div id="up"></div>
            <div id="down">
                <textarea type="text" id="text" style="width: 100%; height: 40px;"></textarea>
            </div>
        </div>
        <input type="button" value="连接" onclick="chat(this);">
        <input type="button" value="发送" onclick="send(this);" disabled="disabled" id="send_btn" title="Enter发送">
    </div>
    <script type="text/javascript">
	    var socket;
	    var receive_text = document.getElementById("up");
	    var send_text = document.getElementById("text");
	    function addText(msg) {
	        receive_text.innerHTML += "<br/>" + msg;
	        receive_text.scrollTop = receive_text.scrollHeight;
	    }
	    var chat = function(obj) {
	        obj.disabled = "disabled";
	        socket = new WebSocket('ws://IP地址:8088/chat/chat');
	        receive_text.innerHTML += "<font color=green>正在连接服务器……</font>";
	        //打开Socket 
	        socket.onopen = function(event) {
	            addText("<font color=green>连接成功!</font>");
	            document.getElementById("send_btn").disabled = false;
	            send_text.focus();
	            document.onkeydown = function(event) {
	                if (event.keyCode == 13 && event.ctrlKey) {
	                    send();
	                }
	            }
	        };
	        socket.onmessage = function(event) {
	            addText(event.data);
	        };
	 
	        socket.onclose = function(event) {
	            addText("<font color=red>连接断开!</font>");
	            obj.disabled = "";
	        };
	        if (socket == null) {
	            addText("<font color=red>连接失败!</font>");
	        }
	    };
	    var send = function(obj) {
	        if (send_text.value == "") {
	            return;
	        }
	        socket.send(send_text.value);
	        send_text.value = "";
	        send_text.focus();
	    }
    </script>
</body>
</html>

3.效果图

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