欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

用JS实现的WebSocket服务器端

程序员文章站 2022-07-12 15:11:39
...

1. 按

一个项目若需用到多种语言开发请参考:基于WebSocket实现的分布式微内核项目

2. 安装库

npm install nodejs-websocket -g

若使用npm安装时一直不动,可以使用cnpm

cnpm install nodejs-websocket -g

NPM:https://www.npmjs.com/package/nodejs-websocket
GitHub:https://github.com/sitegui/nodejs-websocket

3. 代码

console.log("正在创建服务器")

var ws = require("nodejs-websocket")

{
    let port = 56
    var server = ws.createServer(function(conn){
        serverCallbackFunction(conn)
    }).listen(port)
}

function serverCallbackFunction(conn)
{
    console.log("A connection come")
    console.log("Sever connections = ", server.connections.length)
    //when a new message has been received.
    conn.on("text", function(str){ onMesage(str, conn) })

    //when a connection has been closed.
    conn.on("close", function(code, reason){ onClose(conn, code, reason) })

    //when a connection meet error.
    conn.on("error", function(code, reason){ onClose(conn, code, reason); onError(code, reason) })
}

function onMesage(msg, conn)
{
    console.log("收到信息:", msg)
}

function onClose(conn, code, reason)
{
    console.log(conn, "closed", code, reason)
    console.log("Sever connections = ", server.connections.length)
}

function onError(code, reason)
{
    console.log("a connection on error:", code , reason)
}

console.log("创建服务器完毕")
相关标签: WebSocket