文件目录
server.js
这个js文件中写的是主服务器的代码
代码如下
const net = require ( 'net' );
const port = 9000;
const hostname = 'localhost';
const clients = {};
let count = 0;
// 1. 创建服务器
const server = new net.createServer();
// 2. 连接客户端
server.on( 'connection',client=>{
//对客户端进行编号
client.name = ++count;
clients[client.name] = client;
// 3. 获取客户端发来的信息
client.on( 'data',msg=>{
console.log( `客户端${client.name}说:${msg.toString()}` )
boardcast(client,msg.toString())
} )
client.on( 'error',error=>{
console.log(error);
})
client.on( 'close',()=>{
delete clients[client.name];
console.log(`客户端${client.name}已下线`)
})
} )
// 4. 将客户端发来的信息展示到自己的终端上( 广播 )
function boardcast(client,msg){
for(var key in clients){
clients[key].write(msg)
}
}
server.listen( port,hostname,()=>{
console.log(`The server is running at:http://${hostname}:${port}`)
})
client.js
这个js文件加中写的是客户端代码
带如下:
//1. 创建socket
const net = require ( 'net' );
const socket = new net.Socket();
const port = 9000;
const hostname = 'localhost';
const readline = require ( 'readline' );
const rl = readline.createInterface({
input:process.stdin,
output:process.stdout
})
// 2. socket连接服务器
socket.connect(port,hostname,()=>{
socket.write('欢迎到来')
})
socket.on('error',error=>{
console.log(`socket error is ${error}`);
})
socket.on('close',()=>{
console.log(`socket connection closed`);
})
socket.on('data',msg=>{
console.log( msg.toString());
say()
})
function say(){
rl.question('请输入:',answer=>{
if(answer==='bye'){
socket.destroy()
rl.close()
}else{
socket.write(answer)
}
})
}
运行服务器
上面代码写完之后,打开命令终端,进入文件根目录
接着运行server.js
运行客户端
重新打开一个命令终端,运行client.js
此时可以看到已经可以输入消息了,我们可以再打开一个客户端。
打开了两个客户端(可以打开多个客户端),此时的主服务器会显示两个客户端进入
此时,两个客户端就可以聊天啦!