前文说Socket可以再命令行群聊,但我们希望的是用户可以在页面进行群聊
Websocket完美的实现了这个功能
首先,我们应该下载一个ws第三方模块,命令是npm install ws --save如果不想添加package.json则可不写--save
服务器代码为
const WebSocket = require('ws');
const server = new WebSocket.Server({ port: 9000 });
const clients = [];server.on('connection', (client) => {
client.id = clients.length;
clients.push(client); client.on('message', (message) => { for (var i = 0; i < clients.length; i++) { clients[i] && clients[i].send(message); /* 这三行代码等价与上面的一行 if(clients[i]){ clients[i].send(message) }*/ } }); //如果连接出错,把用户移除群聊 client.on('error', () => { clients[client.id] = null; }); //如果用户关闭连接,把用户移出群聊 client.on('close', () => { clients[client.id] = null; });});
HTML端代码
<body>
<input id="input" /> <button id="button" οnclick="handleClick()">提交</button> <div id="content"></div> <script> //在高级浏览器中内置了websocket var client = new WebSocket("ws://127.0.0.1:9000"); input = document.getElementById("input"); content = document.getElementById("content"); function handleClick() { client.send(input.value); } client.onmessage = function(e){ content.innerHTML = e.data; } </script></body>