websocket通信

来源:互联网 发布:dubstep软件下载 编辑:程序博客网 时间:2024/06/11 15:12

JSP页面:

<%@ page contentType="text/html;charset=UTF-8" language="java" %><html><head>    <title>聊天室</title>    <link rel="stylesheet" href="http://cdn.static.runoob.com/libs/bootstrap/3.3.7/css/bootstrap.min.css">    <script type="text/javascript" src="${pageContext.request.contextPath}/statics/js/jquery-3.2.1.js"></script>    <script type="text/javascript" src="${pageContext.request.contextPath}/statics/js/bootstrap.min.js"></script>    <script>        $(function () {            var status = "<%=request.getSession().getAttribute("status")%>";            var chatStatus = 0;            var url = "ws://localhost:8080/webSocket";            var webSocket = null;            webSocket = new WebSocket(url);            //连接关闭的回调方法            webSocket.onclose = function () {                console.log("连接关闭!" + getNowFormatDate());            };            //连接失败的回调方法            webSocket.onerror = function () {                console.log("连接失败!");            };            //连接成功的回调方法            webSocket.onopen = function () {                console.log("连接成功!");            }            //接收到的回调方法            webSocket.onmessage = function (event) {//如果获取到消息,心跳检测重置                console.log("收到的消息: " + event.data);                var json = $.parseJSON(event.data);                var list = "<li>";                list += json.time + "<br>" + "<span class='glyphicon glyphicon-user' style='color: #4B4B4B;'></span>" + json.myName + ": ";                list += json.text;                list += "</li>";                $("#now").html(list);                if (json.chatStatus == 1) {                    status = 1;                }            }            window.onbeforeunload = function () {                webSocket.close();            }            $("#but").click(function () {                webSocket.send(JSON.stringify({                    myName: $("#myName").val(),                    myId: $("#myId").val(),                    otherName: $("#otherName").val(),                    otherId: $("#otherId").val(),                    text: editor.getContent(),                    time: getNowFormatDate(),                    chatStatus: 1                }));            })            if (status == 0) {                $.post(                    "/kuaidi/chatMessage",                    {                        "k_chatOtherId": $("#otherId").val(),                        "k_chatMyId": $("#myId").val()                    },                    function (data) {                        var list = "";                        $.each($.parseJSON(data), function (num, content) {                            list += "<li>";                            list += content.k_chatTime + " " + content.k_chatMyName + ":<br>";                            list += content.k_chatMessage;                            list += "</li>";                            $("#before").html(list);                        })                    }                )            }        })        function getNowFormatDate() {            var myDate = new Date();            myDate.getYear();        //获取当前年份(2位)            myDate.getFullYear();    //获取完整的年份(4位,1970-????)            myDate.getMonth();       //获取当前月份(0-11,0代表1月)            myDate.getDate();        //获取当前日(1-31)            myDate.getDay();         //获取当前星期X(0-6,0代表星期天)            myDate.getTime();        //获取当前时间(从1970.1.1开始的毫秒数)            myDate.getHours();       //获取当前小时数(0-23)            myDate.getMinutes();     //获取当前分钟数(0-59)            myDate.getSeconds();     //获取当前秒数(0-59)            myDate.getMilliseconds();    //获取当前毫秒数(0-999)            myDate.toLocaleDateString();     //获取当前日期            var myTime = myDate.toLocaleTimeString();//获取当前时间            return myDate.toLocaleString();        }    </script></head><body><center>    <input type="hidden" id="myName" name="myName" value="${mapMyInfo.k_username}"/>    <input type="hidden" id="myId" name="myId" value="${mapMyInfo.k_id}"/>    <input type="hidden" id="otherName" name="otherName" value="${mapInfo.k_username}"/>    <input type="hidden" id="otherId" name="otherId" value="${mapInfo.k_id}"/>    <div style="width: 70%;height: 65%;top: 70px;">        <div style="height: 60%;width: 100%;overflow: scroll;">            <ul id="chat">                <ul id="before"></ul>                <ul id="now"></ul>            </ul>        </div>        <div style="height: 40%;width: 100%;">            <textarea id="text" name="text" style="height: 85%;width: 100%;"></textarea>            <button id="but" style="height: 15%;width:20%;float: right;" class="btn btn-primary">发送</button>        </div>    </div></center></body></html>



controller:


package com.springmvc.controller;import com.springmvc.common.JsonCommon;import com.springmvc.model.K_chat;import com.springmvc.service.K_chatService;import javax.websocket.*;import javax.websocket.server.ServerEndpoint;import java.io.IOException;import java.text.SimpleDateFormat;import java.util.Date;import java.util.Map;import java.util.concurrent.CopyOnWriteArraySet;
@ServerEndpoint("/webSocket")public class ChatServer {    private static CopyOnWriteArraySet<ChatServer> webSocket = new CopyOnWriteArraySet<>();    private Session session;    SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");    //连接建立成功调用的方法    @OnOpen    public void onOpen(Session session) {        this.session = session;        webSocket.add(this);        System.out.println("连接成功!" + simpleDateFormat.format(new Date()));    }    //收到客户端消息后调用的方法    @OnMessage    public void onMessage(String message) {        for (ChatServer chatServer : webSocket) {                try {                    Date date = new Date();                    JsonCommon jsonCommon = new JsonCommon();                    Map<String, Object> jsonMap = jsonCommon.getObject(message,Map.class);                    K_chat k_chat = new K_chat();                    k_chat.setK_chatMyName(jsonMap.get("myName").toString());                    k_chat.setK_chatMyId(Integer.parseInt(jsonMap.get("myId").toString()));                    k_chat.setK_chatOtherName(jsonMap.get("otherName").toString());                    k_chat.setK_chatOtherId(Integer.parseInt(jsonMap.get("otherId").toString()));                    k_chat.setK_chatMessage(jsonMap.get("text").toString());                    k_chat.setK_chatTime(simpleDateFormat.format(date));                    K_chatService k_chatService = new K_chatService();                    int result = -1;                    result = k_chatService.add(k_chat);                    if (result > 0) {                        System.out.println("聊天信息存储成功!");                        jsonMap.put("simTime",simpleDateFormat.format(date));                        String json = jsonCommon.getJsonString(jsonMap);                        chatServer.sendMeaasge(json);                    }                } catch (IOException e) {                    e.printStackTrace();                }        }    }    private void sendMeaasge(String message) throws IOException {        this.session.getBasicRemote().sendText(message);    }    @OnError    public void onError(Throwable throwable) {        throwable.printStackTrace();        System.out.println("连接失败!" + simpleDateFormat.format(new Date()));    }    //连接关闭调用的方法    @OnClose    public void onClose() {        webSocket.remove(this);        System.out.println("连接关闭!" + simpleDateFormat.format(new Date()));    }}

注意:要导入websocket-api.jar

原创粉丝点击