JSR356標準Java WebSocket實現多人 or 單人聊天室demo

哇,好長時間沒有寫博客了,最近公司在改善前端技術然咱們學什麼react+antd+dva 這種東西看的我頭昏腦漲,還沒幾天就讓我作技術調研弄弄websocket實現點對點聊天,因而乎就開始茫茫的百度生涯。javascript

正片:首先感謝redstarofsleep這位老哥和他的博客給個人啓發他的博客地址http://redstarofsleep.iteye.com/blog/1974620html

別的不說了直接上代碼了前端

 

import javax.websocket.OnClose;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.util.Iterator;
import java.util.concurrent.ConcurrentHashMap;
import java.util.logging.Logger;

/**
 * @author xuyuhao
 * @version 1.0
 * @since 2018/3/21
 */

@ServerEndpoint(value = "/websocket/{user}")
public class MyServerEndpoint {

    private Session session;
    private static final Logger sysLogger = Logger.getLogger("sysLog");
    //定義一個集合 用於存儲打開通道的用戶
    private static ConcurrentHashMap map = new ConcurrentHashMap();

    @OnOpen
    public void open(Session session, @PathParam(value = "user") String user) {
        //判斷用戶是否重複
        if(!map.containsKey(user)){
            //塞入map中
            map.put(user,session);
        }
        sysLogger.info("*** WebSocket opened from sessionId " + session.getId());
    }

    @OnMessage
    public void inMessage(String message) throws Exception {
        //前端傳過來的信息格式爲 ‘發送人,接收人,信息’
        String[] list = message.split(",");
        message = list[0]+":"+list[2];
        //若是接收人爲全體成員
        if("all".equals(list[1])){
            for (Object o : map.keySet()) {
                ((Session)map.get(o)).getBasicRemote().sendText(message);
            }
        }else{
            //獲取發送人
            Session from = (Session)map.get(list[0]);
            //獲取接收人
            Session to = (Session)map.get(list[1]);
            if(to!=null&&from!=null){
                //發送
                from.getBasicRemote().sendText(message);
                to.getBasicRemote().sendText(message);
            }else {
                from.getBasicRemote().sendText("對方已離線");
            }

        }
    }

    @OnClose
    public String end() throws Exception{
        return "*** WebSocket closed from sessionId " + this.session.getId();
    }


}

 

而後定義幾個頁面直接上代碼了java

<%@ page language="java" contentType="text/html; charset=UTF-8"
         pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <title>Index</title>
    <script type="text/javascript" src="js/jquery-1.7.2.min.js"></script>
    <%session.setAttribute("user", "小明");%>
    <script type="text/javascript">
        var ws = null;
        function startWebSocket() {
            if ('WebSocket' in window)
                ws = new WebSocket("ws://localhost:8084/pt/websocket/小明");
            else if ('MozWebSocket' in window)
                ws = new MozWebSocket("ws://localhost:8084/pt/websocket/小明");
            else
                alert("not support");


            ws.onmessage = function(evt) {
                //alert(evt.data);
                console.log(evt);
                // $("#xiaoxi").val(evt.data);
                setMessageInnerHTML(evt.data);
            };
            function setMessageInnerHTML(innerHTML){
                document.getElementById('message').innerHTML += innerHTML + '<br/>';
            }
            ws.onclose = function(evt) {
                //alert("close");
                document.getElementById('denglu').innerHTML="離線";
            };

            ws.onopen = function(evt) {
                //alert("open");
                document.getElementById('denglu').innerHTML="在線";
                document.getElementById('userName').innerHTML='小明';
            };
        }

        function sendMsg() {
            var fromName = "小明";
            var toName = document.getElementById('name').value;  //發給誰
            var content = document.getElementById('writeMsg').value; //發送內容
            ws.send(fromName+","+toName+","+content);//注意格式
        }
    </script>
</head>
<body onload="startWebSocket();">
<p>聊天功能實現</p>
登陸狀態:
<span id="denglu" style="color:red;">正在登陸</span>
<br>
登陸人:
<span id="userName"></span>
<br>
<br>
<br>

發送給誰:<select id="name">
    <option value="all">全部人</option>
    <option value="小玲">小玲</option>
    <option value="小摩納">小摩納</option>
</select>
<br>
發送內容:<input type="text" id="writeMsg"></input>
<br>
聊天框:<div id="message" style="height: 250px;width: 280px;border: 1px solid; overflow: auto;"></div>
<br>
<input type="button" value="send" onclick="sendMsg()"></input>
</body>
</html>

第二個界面react

<%@ page language="java" contentType="text/html; charset=UTF-8"
         pageEncoding="UTF-8" %>
<!DOCTYPE html>
<html>
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <title>Index</title>
    <script type="text/javascript" src="js/jquery-1.7.2.min.js"></script>
    <%session.setAttribute("user", "小摩納");%>
    <script type="text/javascript">
        var ws = null;

        function startWebSocket() {
            if ('WebSocket' in window)
                ws = new WebSocket("ws://localhost:8084/pt/websocket/小摩納");
            else if ('MozWebSocket' in window)
                ws = new MozWebSocket("ws://localhost:8084/pt/websocket/小摩納");
            else
                alert("not support");


            ws.onmessage = function (evt) {
                //alert(evt.data);
                console.log(evt);
                // $("#xiaoxi").val(evt.data);
                setMessageInnerHTML(evt.data);
            };

            function setMessageInnerHTML(innerHTML) {
                document.getElementById('message').innerHTML += innerHTML + '<br/>';
            }

            ws.onclose = function (evt) {
                //alert("close");
                document.getElementById('denglu').innerHTML = "離線";
            };

            ws.onopen = function (evt) {
                //alert("open");
                document.getElementById('denglu').innerHTML = "在線";
                document.getElementById('userName').innerHTML = '小摩納';
            };
        }

        function sendMsg() {
            var fromName = "小摩納";
            var toName = document.getElementById('name').value;  //發給誰
            var content = document.getElementById('writeMsg').value; //發送內容
            ws.send(fromName + "," + toName + "," + content);//注意格式
        }
    </script>
</head>
<body onload="startWebSocket();">
<p>聊天功能實現</p>
登陸狀態:
<span id="denglu" style="color:red;">正在登陸</span>
<br>
登陸人:
<span id="userName"></span>
<br>
<br>
<br>

發送給誰:<select name="name" id="name">
            <option value="all">全部人</option>
            <option value="小玲">小玲</option>
            <option value="小明">小明</option>
        </select>
<br>
發送內容:<input type="text" id="writeMsg"></input>
<br>
聊天框:
<div id="message" style="height: 250px;width: 280px;border: 1px solid; overflow: auto;"></div>
<br>
<input type="button" value="send" onclick="sendMsg()"></input>
</body>
</html>

第三個界面jquery

<%@ page language="java" contentType="text/html; charset=UTF-8"
         pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <title>Index</title>
    <script type="text/javascript" src="js/jquery-1.7.2.min.js"></script>
    <%session.setAttribute("user", "小玲");%>
    <script type="text/javascript">
        var ws = null;
        function startWebSocket() {
            if ('WebSocket' in window)
                ws = new WebSocket("ws://localhost:8084/pt/websocket/小玲");
            else if ('MozWebSocket' in window)
                ws = new MozWebSocket("ws://localhost:8084/pt/websocket/小玲");
            else
                alert("not support");


            ws.onmessage = function(evt) {
                //alert(evt.data);
                console.log(evt);
                // $("#xiaoxi").val(evt.data);
                setMessageInnerHTML(evt.data);
            };
            function setMessageInnerHTML(innerHTML){
                document.getElementById('message').innerHTML += innerHTML + '<br/>';
            }
            ws.onclose = function(evt) {
                //alert("close");
                document.getElementById('denglu').innerHTML="離線";
            };

            ws.onopen = function(evt) {
                //alert("open");
                document.getElementById('denglu').innerHTML="在線";
                document.getElementById('userName').innerHTML='小玲';
            };
        }

        function sendMsg() {
            var fromName = "小玲";
            var toName = document.getElementById('name').value;  //發給誰
            var content = document.getElementById('writeMsg').value; //發送內容
            ws.send(fromName+","+toName+","+content);//注意格式
        }
    </script>
</head>
<body onload="startWebSocket();">
<p>聊天功能實現</p>
登陸狀態:
<span id="denglu" style="color:red;">正在登陸</span>
<br>
登陸人:
<span id="userName"></span>
<br>
<br>
<br>

發送給誰:<select id="name">
            <option value="all">全部人</option>
            <option value="小摩納">小摩納</option>
            <option value="小明">小明</option>
        </select>
<br>
發送內容:<input type="text" id="writeMsg"></input>
<br>
聊天框:<div id="message" style="height: 250px;width: 280px;border: 1px solid; overflow: auto;"></div>
<br>
<input type="button" value="send" onclick="sendMsg()"></input>
</body>
</html>


這個代碼只是一個小demo,估計後期能改動的點很是多~web

好了 開啓你的聊天之旅吧 ~websocket

相關文章
相關標籤/搜索