server.js文件
var net = require("net");
var server = net.createServer();
var users = [];
server.on('connection', function (socket) {
users.forEach(function (client) {
client.write(socket.remotePort + '进入聊天室》');
});
users.push(socket);
socket.on('data', function (data) {
data = data.toString().trim();
users.forEach(function (uesr) {
if (uesr != socket) {
uesr.write(socket.remotePort + ':' + data)
}
});
})
socket.on('error', function (err) {
console.log(socket.remotePort + '退出聊天室');
})
})
server.listen(3000, function () {
console.log('服务器已经在端口号3000启动监听。。。。。');
})
server.on('error', function () {
console.log('服务器异常退出');
})
client.js文件
var net = require('net');
var socket = net.createConnection({
host: '127.0.0.1',
port: 3000
})
socket.on('connect', function () {
console.log('进入聊天室......');
process.stdin.on('data', function (data) {
socket.write(data.toString().trim());
});
})
socket.on('data', function (data) {
console.log(data.toString().trim());
});
socket.on('error', function (err) {
console.log('服务器异常退出。');
})
|