客户端
html结构
<input type="text"> <button οnclick="sendServer()">send</button>
js代码
const ws = new WebSocket('ws://localhost:8080/')// 参数是要连接的服务器地址 // 已经连接 ws.onopen = () => { // ws.send('大家好') } // 前端接受服务器消息 ws.onmessage = (msg) => { console.log(msg) //欢迎光临 // const content = document.getElementById('content') // content.innerHTML += msg.data + '<br/>' } // 错误的时候触发 ws.onerror = (err) => { console.log(err); } // 服务器断开连接的时候触发 ws.onclose = () => { console.log('closed~'); } //前端向后端发消息 function sendServer(){ let text=document.getElementsByTagName('input')[0].value ws.send(text) }
后端服务器
const WebSocket = require('ws') const ws = new WebSocket.Server({ port: 8080 },()=>{ console.log('socket 服务器开启') }) // 开启一个socket 服务器 ws.on('connection', (client) => { // client 是连接上的客户端对象 console.log('客户端连接') client.send('欢迎光临') //后端向前端发送消息 // client.name = ++ clientName // clients[client.name] = client //接受客户端发送的消息 client.on('message', (msg) => { console.log(msg) // broadcast(client, msg) }) // client.on('close', () => { // delete clients[client.name] // console.log(client.name + ' 离开了~') // }) }) // function broadcast(client, msg) { // for (var key in clients) { // clients[key].send(client.name + ' 说:' + msg) // } // } 注释代码为根据需要而用