

const ws = new WebSocket('ws://127.0.0.1:8080')
ws.onopen = function () {
console.log('ws连接状态:' + ws.readyState);
// 成功则发送一个数据
ws.send('111');
}
ws.onmessage = function(data){
// data.data 就是接收到的数据
}
ws.send(data) // data必须是字符串
ws.onclose = function () {
console.log('ws连接状态:' + ws.readyState);
}
ws.onerror = function (error) {
console.log(error);
}
1. 项目结构

2.app.js 代码
let WebSocketServer = require('ws').Server;
wss = new WebSocketServer({ip: '0.0.0.0', port: 8080 });
let wsolist = []
console.log('启动服务器:ws://127.0.0.1:8080');
wss.on('connection', function (ws, req) {
wsolist.push(ws)
console.log('和客服端' + req.connection.remoteAddress
+ '建立了一个连接,是连接的第'+ (wsolist.length +1) +'个用户');
ws.on('message', function (message) {
console.log(message.toString());
wsolist.forEach((wso) => {
wso.send(message.toString())
})
});
ws.on('close', function close() {
wsolist = wsolist.filter(obj => obj !== ws)
});
});
3. index.html
DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Documenttitle>
<style>
.container{
margin: 10px 0;
border: 1px solid pink;
}
style>
head>
<body>
<h1>websocket聊天室h1>
<div>
<input type="text" placeholder="请输入消息内容" id="msg">
<button id="sendBtn">发送button>
<button id="closeBtn">关闭ws聊天室button>
div>
<div class="container">
div>
body>
html>
4. js 代码
// 1. 获取元素
let msg = document.querySelector('#msg')
let send_btn = document.querySelector('#sendBtn')
let close_btn = document.querySelector('#closeBtn')
let container = document.querySelector('.container')
// 2. 建立ws连接
let ws = new WebSocket('ws://192.168.29.54:8080')
// 3. 实现消息的发送
send_btn.addEventListener('click', function(){
ws.send(msg.value)
msg.value = ''
})
// 4. 实现消息的接收
ws.onmessage = function(data){
console.log(data.data);
container.innerHTML += ` ${data.data}`
}
// 5. 关闭ws连接
close_btn.addEventListener('click', function(){
ws.close()
})
1. 希望本文能对大家有所帮助,如有错误,敬请指出
2. 原创不易,还请各位客官动动发财的小手支持一波(关注、评论、点赞、收藏)
3. 拜谢各位!后续将继续奉献优质好文
4. 如果存在疑问,可以私信我(主页有Q)
