WebSocket

目录结构

package.json

{
  "name": "socket",
  "version": "1.0.0",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "author": "",
  "license": "ISC",
  "devDependencies": {
    "ws": "^4.0.0"
  },
  "description": ""
}

webSocket.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>websocket</title>
    <style>
    #chatroom{
        width: 200px;
        height: 480px;
        border: 2px solid #ddd;
        color:black;
        font-size:22px;
        overflow: auto;
    }
    </style>
</head>
<body>
    <h1>websocket</h1>
    <div id="chatroom"></div>
    <input type="text" placeholder="请输入" id="sayword">
    <button id="sendBtn" οnclick="send()">发送</button>
</body>
<script src="webSocketClient.js"></script>
<script>
    function send(){
        ws.send(sayword.value);
        sayword.value ="";
    }

    document.keyup = function(e){
        if(e.keycode == 13){
            ws.send(sayword.value);
            sayword.value ="";
        }
    }
</script>
</html>

webSocketClient.js

// const ws = new WebSocket("ws://localhost:8500");
const ws = new WebSocket('ws://localhost:8500');
//每个浏览器几乎都有webSocket 对象  "ws://localhost:8500"协议

//client  客户端 监听服务端事件   


//连接服务器
ws.onopen = function(){
    ws.send("大家好")
}


//监听  服务端发来的数据
ws.onmessage = function(e){
    var chatroom = document.getElementById("chatroom");
    chatroom.innerHTML += e.data;
}


//监听服务器 server error  H5写法
// 如果服务器有错误 我们直接关闭

ws.onerror = function(err){
    alert("err" + err);
}


//监听服务器关闭
ws.onclose = function(){
    alert("server is close");
}

webSocketServer.js

var ws = require("ws");

console.log(ws)

const webSocketServer = ws.Server;

const wss = new webSocketServer({port:8500})

var clientMap = {};

var count = 0;

var user = "wh1706";

console.log("服务器socket已经监听完毕")


//监听 client 的连接
wss.on("connection",(ws)=>{
    console.log(`${ws}上线了`)
    count ++;
    ws.name = user+count;
    clientMap[ws.name] = ws;


    //监听发送的消息
    ws.on("message",(msg)=>{
        console.log(msg)
        broadcast(msg,ws)
    })

    //监听client关闭
    ws.on("close",(err)=>{
        console.log(ws.name + "离开了");
        delete clientMap[ws.name]; // 删除对象
        broadcast("系统消息:" +ws.name + "下线了",ws);
    })

})


function broadcast(msg,ws){
    for(var key in clientMap){
        clientMap[key].send(ws.name + " :" + msg + "<br/>");
    }
}

代码下载  git地址点击打开链接

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值