-
간단한 익명 채팅 서버프로그래밍/node.js 2017. 5. 12. 11:22
정말 간단한 node.js 사용한 서버 코드..
- 단순 익명 메세지 채팅이 가능함.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode charactersvar net = require('net'); var server = net.createServer(); server.on('connection', handleConnection); server.listen(1337, function() { console.log('chat server start... %j', server.address()); }); var clients = []; var entitys = {}; var userIndex = 1; function handleConnection(conn) { var remoteAddress = conn.remoteAddress + ':' + conn.remotePort; clients.push(conn); conn.name = "User" + userIndex++; broadcast(conn.name + ' enter the chat\n'); conn.setEncoding('utf8'); conn.on('data', function (message) { broadcast(conn.name + ' : ' + message); }); conn.on('error', function (error) { console.log('error: %s, %j', remoteAddress, error.message); }); conn.on('close', function() { clients.splice(clients.indexOf(conn), 1); broadcast(conn.name + " left the chat\n"); }) } function broadcast(message, sender) { clients.forEach(function (client) { if (client === sender) return; client.write(message); }); process.stdout.write(message) }