node 使用websocket实现一个简易聊天

使用nodejs实现一个简易版聊天程序.

client端

package.json

{
  "name": "client",
  "version": "1.0.0",
  "description": "",
  "main": "server.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "start": "node server.js"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "dependencies": {
    "express": "^4.18.2"
  }
}

server.js

const express = require("express");
const path = require("path");
const port = 4000;
const app = new express();

app.use(express.static(path.resolve(__dirname, "public")));


app.listen(port, () => {
    console.log(`Client server run at ${port}.`);
})

public/index.html





    
    
    
    Document
    



    

server端

package.json

{
  "name": "server",
  "version": "1.0.0",
  "description": "",
  "main": "server.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "start": "node server.js"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "dependencies": {
    "express": "^4.18.2",
    "ws": "^8.11.0"
  }
}

server.js

/**
 * 数据结构
 * get:
 * type message/status
 * data {sender,receriver,message}/{user,status: //0 offline 1 online}
 * 
 * send:
 * {receiver,message}
*/

const MESSAGE_TYPE = {
    MESSAGE: "message",
    STATUS: "status",
};

const STATUS = {
    ONLINE: 1,
    OFFLINE: 0,
}

const Websocket = require("ws");
const url = require("url");
const port = 4005;

const wss = new Websocket.Server({ port: port });

wss.on("connection", (ws, req) => {
    const parameters = url.parse(req.url, true);
    ws.name = parameters.query.name;

    //notice all the client that somebody is login
    wss.clients.forEach(client => {
        //skip self
        if (client.name == ws.name) {
            return;
        }

        let msg = JSON.stringify({
            type: MESSAGE_TYPE.STATUS,
            data: {
                status: STATUS.ONLINE,
                user: ws.name,
            }
        });
        client.send(msg)
    })

    ws.on("message", (e) => {
        const data = JSON.parse(e.toString());
        const { receiver } = data;
        wss.clients.forEach(client => {
            if (client.name == receiver) {
                let msg = JSON.stringify({
                    type: MESSAGE_TYPE.MESSAGE,
                    data: {
                        ...data,
                        sender: ws.name,
                    },
                })
                client.send(msg);
            }
        })
    })

    ws.on("close", (e) => {
        wss.clients.forEach(client => {
            let msg = JSON.stringify({
                type: MESSAGE_TYPE.STATUS,
                data: {
                    status: STATUS.OFFLINE,
                    user: ws.name,
                }
            });
            client.send(msg)
        })
    })
})

演示效果

你可能感兴趣的:(node 使用websocket实现一个简易聊天)