js WebSocket封装

//浏览器WebSocket对象
var wsImpl = window.WebSocket || window.MozWebSocket;
function SocketStart(options, cl) {
    this.url = options.url;//Socket地址
    this.ws = new wsImpl(options.url);//初始化Socket对象
    this.userid = options.userid;//用户id
    this.onmessage = options.onmessage;//接受消息回调函数
    this.onopen = options.onopen;//连接成功回调函数
    this.onclose = options.onclose;//连接断开回调函数
    this.dataType = options.dataType || 'json';//json或txt格式数据 默认json
    var _self = this;
    SocketInit(_self)
}

function SocketInit(_self) {
    //setTimeout
    var loopTime;
    /**
     * 发送消息方法
     * msg 消息内容,字符串或json都可以
     * touser 接受方id
     */
    _self.send = function (msg,touser) {
        // 组装消息
        var msg = {
            userid: _self.userid,
            touser:touser,
            msg: msg
        }
        //转字符串
        var msgstr=JSON.stringify(msg);
        //获取消息字符串字节长度
        var msglength=msgstr.StrLength();
        //判断是否超过限制
        if(msglength>4000){
            console.error("消息内容过长!");
            return;
        }

        // 发送消息
        try {
            _self.ws.send(msgstr);
        } catch (error) {
            console.log(error)
        }

    }

    /**
     * 接收消息事件
     */
    _self.ws.onmessage = function (evt) {
        // 判断消息是否为空
        if (!evt.data) {
            return;
        }

        //判断消息类型
        var get_data;
        if (_self.dataType == 'json') {
            get_data = JSON.parse(evt.data)
        } else {
            get_data = evt.data
        }

        //判断消息是否为心跳
        if (get_data.msg == '__loop__') {
            return;
        }
        // 连接成功
        if (get_data.msg == "__success__") {
            console.log("连接成功!");
            return;
        }

        //调用回调函数
        if (_self.onmessage) {
            _self.onmessage(get_data.msg,get_data.userid,get_data);
        }

    };
    //连接成功事件
    _self.ws.onopen = function () {
        // 调用心跳函数 第一次发送内容为  __success__
        loop("__success__");

        //调用回调函数
        if (_self.onopen) {
            _self.onopen();
        }
    };

    //断开连接事件
    _self.ws.onclose = function () {
        clearTimeout(loopTime);
        console.error("连接断开!");
        console.log("重新连接!");

        
        //调用回调函数
        if (_self.onclose) {
            _self.onclose();
        }

        //1秒后重连
        setTimeout(function () {
            _self.ws = new wsImpl(_self.url);
            SocketInit(_self)
        }, 1000);
    }

    //心跳函数 递归执行 10秒一次,接收方为自己
    function loop(i) {
        _self.send((i || "__loop__"),_self.userid);
        loopTime = setTimeout(function () {
            loop();
        }, 10000);
    }
}

/**
 * 获取字符串字节长度
 */
function StrLength(){
    var num=0;
    for (var i = 0; i < this.length; i++) {
        var charCode=this[i].charCodeAt(0);
        if (charCode < 0x007f)  {  
            num++;
        }
        else if ((0x0080 <= charCode) && (charCode <= 0x07ff))  {  
            num+=2;
        }
        else if ((0x0800 <= charCode) && (charCode <= 0xffff))  {  
            num+=3;
        }else{
            num+=4;
        }
    }
    return num;
}
/**
 * 获取字符串字节长度
 */
String.prototype.StrLength=StrLength;

使用

<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>

<body>
    <span id="userid">

    </span>
    <br>
    <input type="text" name="" id="touser" placeholder="接收方id">
    <br>
    <button id="send">发送消息</button>
    <br>
    <textarea id="msg" name="" id="" cols="60" rows="20"  placeholder="消息内容"></textarea>
    <br>
    <textarea id="getmsg" name="" id="" cols="60" rows="20" placeholder="接收消息"></textarea>
    <pre id="incomming"></pre>
    <script src="jquery-3.4.1.min.js"></script>
    <script src="SocketStart.js"></script>
    <script type="text/javascript">
        $(function () {
            var userid = "aa" + Math.ceil(Math.random() * 100000);
            $("#userid").text(userid)
            var ss = new SocketStart({
                url: "ws://localhost/Socket",
                userid: userid,
                onopen: function () {
                    console.log(666);
                },
                onclose: function () {
                    console.error(666);
                },
                onmessage: function (msg, userid,get_data) {
                    console.log(msg)//收到的消息内容
                    console.log(userid)//发送者的id
                    console.log(get_data)//接收到的完整数据
                    $("#getmsg").val(msg)
                },
            });

            //发送消息
            $("#send").click(function (e) {
                ss.send($("#msg").val(), $("#touser").val())
            });

        })

    </script>
</body>

</html>

后端代码 C#

我们可以使用 JavaScript 中的 `WebSocket` 对象来创建一个 WebSocket 连接,然后封装一些常用的方法来简化操作。以下是一个简单的封装示例: ```javascript class WebSocketClient { constructor(url) { this.url = url; this.websocket = null; this.isConnected = false; this.connect(); } connect() { this.websocket = new WebSocket(this.url); this.websocket.onopen = () => { this.isConnected = true; console.log('WebSocket 连接成功'); }; this.websocket.onmessage = (event) => { console.log('收到消息:', event.data); }; this.websocket.onclose = () => { this.isConnected = false; console.log('WebSocket 连接关闭'); }; this.websocket.onerror = (error) => { console.error('WebSocket 错误:', error); }; } send(message) { if (this.isConnected) { this.websocket.send(message); console.log('发送消息:', message); } else { console.error('WebSocket 连接未建立'); } } close() { if (this.isConnected) { this.websocket.close(); console.log('WebSocket 连接关闭'); } else { console.error('WebSocket 连接未建立'); } } } ``` 使用示例: ```javascript const ws = new WebSocketClient('ws://localhost:8080'); ws.send('Hello, WebSocket!'); ws.close(); ``` 在上面的示例中,我们使用 `WebSocketClient` 类来封装了一个 WebSocket 客户端,提供了 `connect`、`send` 和 `close` 方法。其中,`connect` 方法用于建立 WebSocket 连接,`send` 方法用于发送消息,`close` 方法用于关闭连接。在创建实例时,会自动调用 `connect` 方法来建立连接。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

weixin_42199478

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

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

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

打赏作者

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

抵扣说明:

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

余额充值