Skip to content

Instantly share code, notes, and snippets.

@huzemin
Created January 19, 2016 13:05
Show Gist options
  • Save huzemin/6da130dd9d4bc764cf41 to your computer and use it in GitHub Desktop.
Save huzemin/6da130dd9d4bc764cf41 to your computer and use it in GitHub Desktop.
Create a simple real time chat by node.
var net = require('net');
var readline = require('readline');
var HOST = process.env.IP,
PORT = process.env.PORT;
var me = readline.createInterface(process.stdin, process.stdout);
var client = new net.Socket();
client.connect(PORT, HOST, function() {
console.log('CONNECTED TO: ' + HOST + ':' + PORT);
// send message to server.
say(client, 'Please enter your name:');
});
client.on('data', function(data) {
me.write(null, {ctrl: true, name: 'u'});
me.pause();
console.log(data.toString('utf-8'));
me.resume();
me.prompt();
});
function say(client, title) {
me.question(title +'\t', function(data) {
if(data == 'quit') {
me.close();
client.destroy();
return;
}
if(data == '') {
say(client, title);
} else {
client.write(data);
say(client, 'me>');
}
});
}
client.on('close', function() {
console.log('Connection closed');
});
client.on('error', function() {
console.log('Connected error!')
process.exit(0);
})
process.on('SIGINT', function() {
console.log('Exit');
client.end();
});
var net = require('net');
var host = process.env.IP,
port = process.env.PORT;
var clients = [];
var server = net.createServer(function(sock) {
// socket客户端标识
sock.name = sock.remoteAddress + ':' + sock.remotePort;
if(clients.indexOf(sock) == -1) {
console.log('hello' + sock.name);
// 添加到客户端数组
clients.push(sock);
}
// 广播消息欢迎消息
broadcast(sock, 'Welcome ' + sock.name);
// 为这个socket实例添加一个"data"事件处理函数
sock.on('data', function(data) {
broadcast(sock, sock.name + ' > ' + data);
});
// 为这个socket实例添加一个"close"事件处理函数
sock.on('close', function(data) {
broadcast(sock, sock.name + "## exit");
clients.slice(clients.indexOf(sock), 1);
});
sock.on('error', function(err) {
console.log(sock.name + " : " + err.message);
});
// 广播消息
function broadcast(sender, message) {
message = "\n" + message;
clients.forEach(function(sock){
if( sock == sender) {
return;
}
sock.write(message);
});
process.stdout.write('BroadCast:' + message);
}
}).listen(port, host);
console.log('Server listening on ' + host +':'+ port);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment