net-socket 聊天室效果
- server.js 先创建个服务器
```javascript
const net = require('net');
const port = 8080;
const hostname = '10.31.163.20';
const server = new net.createServer();
const clients = {};
let clinenum = 0;
server.on('connection', (client) => { //连接客户端
client.name = ++clinenum //不同客户端编号
clients[client.name] = client
client.on('data', (msg) => { //获取客户端发来的信息
console.log(`客户端${client.name}发来信息>${msg}`)
for (let key in clients) {
clients[key].write(`客户端${client.name}发来信息>${msg}`)
}
})
client.on('error', (e) => {
console.log(`错误是${e}`)
});
client.on('close', (clineName) => { //客户端下线,提示信息
delete clients[client.name]
console.log(`客户端${client.name}已下线`)
});
});
server.listen(port, hostname, () => { //监听服务器
console.log(`server is running at:http://${hostname}:${port}`)
})
```
- client.js 创建客户端
const net = require('net'); const socket = new net.Socket(); const port = 8080; const hostname = '10.31.163.20'; const readline = require('readline'); const rl = readline.createInterface({ // 创建接口,进行信息的读写 input: process.stdin, output: process.stdout }) socket.connect(port, hostname, () => { socket.write('大家好') }) socket.on('data', () => { rl.question('请输入', (answer) => { if (answer === 'bye') { //如果输入bye就关闭客户端 socket.destroy() rl.end() } else { socket.write(answer + '\n') } }) }) socket.on('error', (e) => { console.log(`错误是${e}`) }); socket.on('close', () => { console.log('客户端已下线') })
首先运行server.js,然后可以运行多个client.js模拟多个客户端操作