Nodejs is a simple chat server.
The implementation code is as follows:
Var net = require ('net'); var chatServer = net. createServer (), clientList = []; chatServer. on ("connection", function (client) {client. name = client. remoteAddress + ":" + client. remotePort; client. write ("Hi! "+ Client. name + "\ n"); clientList. push (client); client. on ("data", function (data) {// send data to the client broadcast (data, client); // clientList [I]. write (data) ;}); client. on ("end", function () {clientList. splice (clientList. indexOf (client), 1) ;}); client. on ("error", function (e) {console. log (e)}) ;}); chatServer. listen (9000) function broadcast (message, client) {var cleanup = []; for (var I = 0; I <clientList. length; I ++) {if (Client! = ClientList [I]) {if (clientList [I]. writable) {clientList [I]. write (client. name = "says:" + message);} else {cleanup. push [clientList [I]; clientList [I]. destory ();}}}}
The procedure is as follows:
Start js
node chat.js
Connection Method: telnet
telnet 127.0.0.1 9000