客户端的使用


1、在 .Net 中使用

  使用 WebSocketClient 连接到 websocket 服务地址,然后发送消息,如下所示:

[TestMethod]
public async Task TestSendMessage()
{
    var client = new WebSocketClient();
    await client.StartAsync("ws://localhost:5001/wsChat");
    //方法定义参照上一节
    await client.SendAsync("Send", 1, 1, "这是来自 admin 的提醒。");
    await client.CloseAsync();
}

2、在 JavaScript 中使用

// 初始化一个 WebSocket 对象
var ws = new WebSocket("ws://localhost:5001/wsChat");

// 建立 websocket 连接成功触发事件
ws.onopen = function () {
    console.log("连接成功");
    
    //发送消息
    ws.send('{M:"Send",A:[1, 1, "这是来自 admin 的提醒。"]}');
};

// 当服务端处理完成后会将数据发送回来
ws.onmessage = function (evt) {
    var data = JSON.parse(evt.data)
    console.log(data)

    if (data.M === 'OnReceiveNotify') {
        alert(data.A[0]);
    }
};

// 心跳
setInterval(function () {
    if (ws.readyState !== 1) {
        return;
    }

    console.log('send hearting...');
    ws.send(String.fromCharCode(0)); //0为心跳标识
}, 10000);

  以下是一个简易的封装:

function websocket(opts) {
    opts = $.extend(opts, { hearting: 20000 });

    var ws = new WebSocket(opts.url);

    var _this = this;

    // 建立 websocket 连接成功触发事件
    ws.onopen = function () {
        if (opts.onConnected !== undefined) {
            opts.onConnected(_this);
        }
    };

    // 当服务端处理完成后会将数据发送回来
    ws.onmessage = function (evt) {
        var data = JSON.parse(evt.data)

        if (opts.onReceived !== undefined) {
            opts.onReceived(data.M, data.A);
        }

        if (opts[data.M] !== undefined) {
            opts[data.M].apply(this, data.A);
        }
    };

    // 心跳
    setInterval(function () {
        if (ws.readyState !== 1) {
            return;
        }

        console.log('send hearting...');
        ws.send(String.fromCharCode(0));
    }, opts.hearting);

    //发送消息
    this.send = function () {
        var args = [];
        var m = arguments[0];
        for (var i = 1; i < arguments.length; i++) {
            args.push(arguments[i]);
        } 
        ws.send('{M:"' + m + '",A:' + JSON.stringify(args) + '}')
    }
}

  使用方法如下所示:

// 初始化一个 WebSocket 对象
var opts = {
    url: "ws://localhost:5001/wsChat",
    onConnected: function (ws) {
        ws.send('Connect', 1, 1, "admin");
    },
    onUpdateOnlineList: function (users) {
        $('#online').text(users.length);
        for (var i = 0; i < users.length; i++) {
            console.log(users[i].name);
        }
    },
    onNotifyOnline: function (name) {
        alert(name + '上线了!');
    },
    onNotifyOffline: function (name, count) {
        alert(name + '下线了!');
    }
};
var ws = new websocket(opts);