xgqfrms™, xgqfrms® : xgqfrms's offical website of cnblogs! xgqfrms™, xgqfrms® : xgqfrms's offical website of GitHub!

IM & WebSockets All In One

IM & WebSockets All In One

WebSocket API

https://developer.mozilla.org/en-US/docs/Web/API/WebSockets_API

https://developer.mozilla.org/en-US/docs/Web/API/WebSocket


// Create WebSocket connection.
const socket = new WebSocket('ws://localhost:8080');

// Connection opened
socket.addEventListener('open', function (event) {
    socket.send('Hello Server!');
});

// Listen for messages
socket.addEventListener('message', function (event) {
    console.log('Message from server ', event.data);
});

Node.js & websokets server / websokets client

server


"use strict";

/**
 *
 * @author xgqfrms
 * @license MIT
 * @copyright xgqfrms
 *
 * @description WS
 * @augments
 * @example
 *
 */

// const WSGenerator = (datas = [], debug = false) => {
//     let result = ``;
//     // do something...
//     return result;
// };



// export default WS;

// export {
//     WS,
// };

const WebSocket = require('ws');

const wss = new WebSocket.Server({
    // host: "",
    // path: "",
    port: 8888
});

let counter = 1;

wss.on('connection', function (ws, req) {
    console.log("client connected", counter);
    counter ++;
    ws.on("message", function (msg) {
        console.log(`receive message = `, msg);
        if (ws.readyState === 1) {
            const json = {
                "success": true,
                "message": null,
                "data": [
                    {
                        "pro_name": "otc",
                        "pro_instructions": null,
                        "pro_type_name": "front-end",
                        "send_time": null,
                        "incre": true,
                    },
                    {
                        "pro_name": "ds",
                        "pro_instructions": null,
                        "pro_type_name": "back-end",
                        "send_time": null,
                        "incre": false
                    }
                ]
            };
            // const json = {
            //     success: true,
            //     message: "success",
            //     data: []
            // };
            let datas = JSON.stringify(json);
            // return json datas;
            ws.send(datas);
            // ws.send("server returned message!");
        }
    });
    let ip = req.connection.remoteAddress;
    console.log(`ip =`, ip);
});


client


"use strict";

/**
 *
 * @author xgqfrms
 * @license MIT
 * @copyright xgqfrms
 *
 * @description WS
 * @augments
 * @example
 *
 */

// const WS = (datas = [], debug = false) => {
//     let result = ``;
//     // do something...
//     return result;
// };



// export default WS;

// export {
//     WS,
// };


const url = `ws://10.1.64.138:8888/F10_APP/src/test`;
let ws = new WebSocket(url);

ws.onopen = function(e) {
    console.log(`已经建立连接 open`, ws.readyState);
    console.log(`e = `, e);
};

ws.onerror = function(e) {
    console.log(`连接异常 error`, ws.readyState);
    console.log(`e = `, e);
};

ws.onmessage = function(res) {
    console.log(`收到消息 message`, ws.readyState);
    let data = res.data,
        origin = res.origin;
    console.log(`res & e = `, res);
    console.log(`res.data = `, res.data);
    console.log(`res.origin = `, res.origin);
};

ws.onclose = function(e) {
    console.log(`已经关闭连接 close`, ws.readyState);
    console.log(`e = `, e);
};


setTimeout(() => {
    ws.onopen = function(e) {
        console.log(`已经建立连接 open`, ws.readyState);
        console.log(`e = `, e);
    };
}, 1000 * 1);



ws client

new version


"use strict";

/**
 * 
 * @author xgqfrms
 * @license MIT
 * @copyright xgqfrms
 * 
 * @description WS client
 * @augments 
 * @example 
 * @link 
 * 
 */


const url = `ws://192.168.1.36:8888/`;
let ws = new WebSocket(url);

let log = console.log;

ws.onopen = function(e) {
    log(`已经建立连接 open`, ws.readyState);
    log(`e = `, e);
};

ws.onerror = function(e) {
    log(`连接异常 error`, ws.readyState);
    log(`e = `, e);
};

ws.onmessage = function(res) {
    log(`收到消息 message`, ws.readyState);
    let data = res.data;
    let origin = res.origin;
    log(`res & e = `, res);
    log(`res.data = `, JSON.stringify(data, null, 4));
    log(`res.origin = `, origin);
};

ws.onclose = function(e) {
    log(`已经关闭连接 close`, ws.readyState);
    log(`e = `, e);
};


setTimeout(() => {
    ws.onopen = function(e) {
        log(`已经建立连接 open`, ws.readyState);
        log(`e = `, e);
    };
}, 1000 * 1);

// setTimeout(() => {
//     ws.send(`hello server!`);
// }, 3000);

let flag = setInterval(() => {
    ws.send(`hello server!`);
}, 3000);

setTimeout(() => {
    clearInterval(flag);
}, 60 * 1000);

websocket & readyState

https://developer.mozilla.org/en-US/docs/Web/API/WebSocket/readyState

(🐞 反爬虫测试!打击盗版⚠️)如果你看到这个信息, 说明这是一篇剽窃的文章,请访问 https://www.cnblogs.com/xgqfrms/ 查看原创文章!

refs



©xgqfrms 2012-2021

www.cnblogs.com/xgqfrms 发布文章使用:只允许注册用户才可以访问!

原创文章,版权所有©️xgqfrms, 禁止转载 🈲️,侵权必究⚠️!


posted @ 2019-06-21 22:16  xgqfrms  阅读(238)  评论(15编辑  收藏  举报