Create simple chat rooms for Node. js and simple chat rooms for node. js

Source: Internet
Author: User

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.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.