WebSocket模拟微信(及时通讯功能)

7 篇文章 0 订阅

废话不对说直接上代码,下面是jsp代码:

<%--
  Created by IntelliJ IDEA.
  User: Administrator
  Date: 2021/4/7
  Time: 15:11
  To change this template use File | Settings | File Templates.
--%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<%@ page contentType="text/html; charset=UTF-8"%>
<%@ include file="/WEB-INF/pages/system/tag.jsp"%>
<html>
<head>
    <meta charset="utf-8">
    <title>聊天室</title>
    <meta name="renderer" content="webkit">
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
    <link rel="stylesheet" href="${baseurl}/layuimin/lib/layui/css/layui.css" media="all">
    <link rel="stylesheet" href="${baseurl}/layuimin/css/public.css" media="all">
    <style type="text/css">
        .noscript {
            align-content: center;
            margin-top: 20px;
        }
        
        #console-container {
            width: 400px;
        }

        #console {
            border: 1px solid #CCCCCC;
            border-right-color: #999999;
            border-bottom-color: #999999;
            height: 600px;
            overflow-y: scroll;
            padding: 5px;
            width: 100%;
        }

        #console p {
            padding: 0;
            margin: 0;
        }
    </style>
    <script type="text/javascript">
        var Chat = {};
        Chat.socket = null;

        Chat.connect = (function(host) {
            if ('WebSocket' in window) {
                Chat.socket = new WebSocket(host);
            } else if ('MozWebSocket' in window) {
                Chat.socket = new MozWebSocket(host);
            } else {
                Console.log(' Info:你的浏览器不支持WebSocket【聊天室】.');
                return;
            }

            Chat.socket.onopen = function () {
                Console.log('Info:聊天室链接打开...');
                document.getElementById('chat').onkeydown = function(event) {
                    if (event.keyCode == 13) {
                        Chat.sendMessage();
                    }
                };
                //心跳检测重置
                heartCheck.start();
            };

            Chat.socket.onclose = function () {
                document.getElementById('chat').onkeydown = null;
                Console.log('Info:聊天室链接关闭...');
            };

            Chat.socket.onmessage = function (message) {
                Console.log(message.data);
            };
        });

        Chat.initialize = function() {
            if (window.location.protocol == 'http:') {
                Chat.connect('ws://' + window.location.host + '/项目名/websocket/chat/${username}');// ${username} 自己带的动态值,我这里其实是进入页面带过来的IP,你可以自己带姓名或者其他的都可以
            } else {
                Chat.connect('wss://' + window.location.host + '/项目名/websocket/chat/${username}');
            }
        };

        Chat.sendMessage = (function() {
            var message = document.getElementById('chat').value;
            if (message != '') {
                Chat.socket.send(message);
                document.getElementById('chat').value = '';
            }
            //拿到任何消息都说明当前连接是正常的
            heartCheck.start();
        });

        var Console = {};

        Console.log = (function(message) {
            var console = document.getElementById('console');
            var p = document.createElement('p');
            p.style.wordWrap = 'break-word';
            p.innerHTML = message;
            console.appendChild(p);
            // 对话框保留100条数据,多余100条删除
            while (console.childNodes.length > 100) {
                console.removeChild(console.firstChild);
            }
            console.scrollTop = console.scrollHeight;
        });

        Chat.initialize();

        document.addEventListener("DOMContentLoaded", function() {
            // Remove elements with "noscript" class - <noscript> is not allowed in XHTML
            var noscripts = document.getElementsByClassName("noscript");
            for (var i = 0; i < noscripts.length; i++) {
                noscripts[i].parentNode.removeChild(noscripts[i]);
            }
        }, false);

        //心跳检测 3分钟
        var heartCheck = {
            timeout: 180000,
            timeoutObj: null,
            serverTimeoutObj: null,
            start: function () {
                console.log('start');
                var self = this;
                this.timeoutObj && clearTimeout(this.timeoutObj);
                this.serverTimeoutObj && clearTimeout(this.serverTimeoutObj);
                this.timeoutObj = setTimeout(function () {
                    //发送测试信息,后端收到后,返回一个消息,
                    Chat.socket.send("Status:自动响应...");
                    self.serverTimeoutObj = setTimeout(function () {
                        Chat.socket.close();
                    }, self.timeout);
                }, this.timeout)
            }
        }
    </script>
</head>
<body style="margin-left: 5%;">
<fieldset class="layui-elem-field layui-field-title" style="margin-top: 20px;">
    <legend>聊天室©0.1</legend>
</fieldset>
<div class="noscript">
    <h2 style="color: #ff0000">Seems your browser doesn't support Javascript! Websockets rely on Javascript being enabled. Please enable
        Javascript and reload this page!</h2>
</div>
<div class="noscript">
    <div class="layui-form-item">
        <p>
            <input type="text" placeholder="请输入聊天内容,Enter键发送" id="chat" class="layui-input" style="width:413px"/>
        </p>
    </div>
    <div class="layui-form-item">
        <div id="console-container">
            <div id="console"/>
        </div>
    </div>
</div>
</body>
</html>

java代码:

package com.mlwy.controller.test.socket;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.CopyOnWriteArraySet;
import javax.websocket.OnClose;
import javax.websocket.OnError;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;

import com.mlwy.util.Util;
import org.apache.log4j.Logger;
/**
 * WebSocket 消息推送服务类
 * @author chenchbj
 * 20210407
 */
@ServerEndpoint(value = "/websocket/chat/{username}")
public class ChatAnnotation {

    private static final Logger log = Logger.getLogger(ChatAnnotation.class);

    private static final Map<String,Object> connections = new HashMap<String,Object>();

    private static CopyOnWriteArraySet<ChatAnnotation> webSocketSet = new CopyOnWriteArraySet<>();

    private  String username;
    private Session session;

    @OnOpen
    public void start(Session session,@PathParam("username") String username) {
        this.session = session;
        this.username = username;
        connections.put(username, this);
        webSocketSet.add(this);
        String message = String.format(" %s %s", username, "进入- - - - - - - - - - - - - - - - - - ");
        broadcast(message);
    }


    @OnClose
    public void end() {
        connections.remove(this);
        String message = String.format(" %s %s",
                username, "退出- - - - - - - - - - - - - - - - - - ");
        broadcast(message);
    }


    /**
     * 消息发送触发方法
     * @param message
     */
    @OnMessage
    public void incoming(String message) {
        // Never trust the client
        String filteredMessage = String.format("%s: %s",
                username, HTMLFilter.filter(message.toString()));
        broadcast(filteredMessage);
        Util.ChatLogTxt("------时间:"+Util.getNow(null),
                filteredMessage,Util.getNowDay(null));
    }

    @OnError
    public void onError(Throwable t) throws Throwable {
        log.error("Chat Error: " + t.toString(), t);
    }

    /**
     * 消息发送方法
     * @param msg
     */
    private static void broadcast(String msg) {
        if(msg.indexOf("admin")!=-1){
            sendUser(msg);
        } else{
            sendAll(msg);
        }
    }
    /**
     * 向所有用户发送
     * @param msg
     */
    public static void sendAll(String msg){
        for (String key : connections.keySet()) {
            ChatAnnotation client = null ;
            try {
                client = (ChatAnnotation) connections.get(key);
                synchronized (client) {
                    if (client.session.isOpen() == true){
                        client.session.getBasicRemote().sendText(msg);
                    }else {
                        log.info(client.username+":客户端已经关闭");
                    }
                }
            } catch (IOException e) {
                log.debug("Chat Error: Failed to send message to client", e);
                connections.remove(client);
                try {
                    client.session.close();
                } catch (IOException e1) {
                    // Ignore
                }
                String message = String.format("* %s %s",
                        client.username, "has been disconnected.");
                broadcast(message);
            }
        }
    }
    /**
     * 向指定用户发送消息 admin
     * @param msg
     */
    public static void sendUser(String msg){
        ChatAnnotation c = (ChatAnnotation)connections.get("admin");
        try {
            c.session.getBasicRemote().sendText(msg);
        } catch (IOException e) {
            log.debug("Chat Error: Failed to send message to client", e);
            connections.remove(c);
            try {
                c.session.close();
            } catch (IOException e1) {
                // Ignore
            }
            String message = String.format("* %s %s",
                    c.username, "has been disconnected.");
            broadcast(message);
        }
    }
}
package com.mlwy.controller.test.socket;

/**
 * HTML 工具类
 *
 * @author chenchbj
 */
public final class HTMLFilter {
    public static String filter(String message) {
        if (message == null){
            return (null);
        }
        char content[] = new char[message.length()];
        message.getChars(0, message.length(), content, 0);
        StringBuilder result = new StringBuilder(content.length + 50);
        for (int i = 0; i < content.length; i++) {
            switch (content[i]) {
                case '<':
                    result.append("<");
                    break;
                case '>':
                    result.append(">");
                    break;
                case '&':
                    result.append("&");
                    break;
                case '"':
                    result.append("'");
                    break;
                default:
                    result.append(content[i]);
            }
        }
        return (result.toString());
    }
}

pom.xml

<dependency>
      <groupId>javax.websocket</groupId>
      <artifactId>javax.websocket-api</artifactId>
      <version>1.1</version>
      <scope>provided</scope>
    </dependency>
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

SuperChen12356

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值