websocket
var net = require('net');
var chatServer = net.createServer(),
clientList = [];
clientMap=new Object();
var ii=0;
chatServer.on('connection', function(client) {
// JS 可以为对象自由添加属性。这里我们添加一个 name 的自定义属性,用于表示哪个客户端(客户端的地址+端口为依据)
client.name = client.remoteAddress + ':' + client.remotePort;
client.write('Hi ' + client.name + '!\n');
clientList.push(client);
client.name=++ii;
clientMap[client.name]=client;
client.setEncoding('utf-8');
//超时事件
client.setTimeout(timeout, function(){
console.log('连接超时');
client.end();
});
client.on('data', function(data) {
console.log('客户端传来:'+data);
//client.write('你发来:'+data);
broadcast(data, client); // 接受来自客户端的信息
});
//数据错误事件
client.on('error', function(exception){
console.log('client error:' + exception);
client.end();
});
//客户端关闭事件
client.on('close', function(data){
delete clientMap[client.name];
console.log(client.name+'下线了');
broadcast(client.name+'下线了', client);
});
});
function broadcast(message, client) {
for(var key in clientMap){
clientMap[key].write(client.name+'say:'+message+'\n');
}
}
chatServer.listen(9000);
4. SocketClient.js
var net = require('net');
var port = 9000;
var host = '127.0.0.1';
var client= new net. Socket();
client.setEncoding('UTF-8');
//client.setEncoding('binary');
//连接到服务端
client.connect(port, host, function(){
client.write('你好');
});
client.on('data', function(data){
console.log('服务端传来:'+ data);
say();
});
client.on('error', function(error){
console.log('error:'+error);
//client.destory();
});
client.on('close', function(){
console.log('Connection closed');
});
//----------------------------------------------------------
const readline = require('readline');
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout
});
function say(){
rl.question('请输入: ', (inputStr) => {
if(inputStr!='bye'){
client.write(inputStr+'\n');
say();
}else{
client.destroy(); //关闭连接
rl.close();
}
});
}最后更新于