Create simple chat rooms for Node. js and simple chat rooms for node. js
I read about TCP and wrote a NET-based chat room.
Var net = require ('net'); var count = 0, users ={}; var server = net. createServer (function (conn) {console. log ('connection'); conn. write ("\ r \ n> welcome to node-chat! "+" \ R \ n> "+ count +" other people are connected at this time. "+" \ r \ n> please write your name and press enter: "); count ++; // represents the nickname var nickname; console for the current connection. log (conn); conn. on ('data', function (data) {// Delete \ r \ n // data = data. replace ('\ r \ n', ''); // The currently registered nickname does not exist if (! Nickname) {// the user name has if (users [data]) {conn. write ('nickname in use'); return;} else {// give the username nickname = data; users [nickname] = conn; for (var I in users) {users [I]. write ('\ r \ n>' + nickname + 'join our room \ r \ n> I :');}}} else {// start chatting for (var I in users) {if (I! = Nickname) {users [I]. write ('\ r \ n>' + nickname + ':' + data) ;}}}); conn. on ('close', function () {count --;}); conn. setEncoding ('utf8');}); server. listen (3000, function () {console. log ('server listening port 3000 ');})
Run:
Terminal:
Telnet: Two netizens are intercepted.
The above is all the content of this article. I hope it will be helpful for your learning and support for helping customers.