[NodeJS] use Node. js to write a simple online chat room

Source: Internet
Author: User

Disclaimer: the tutorial is from "out-of-the-box use of Node". Source code cases are all from this book. Blog posts are for personal study notes only.


Step 1: Create a chat server.

First, let's write a Server:

var net = require('net')var chatServer = net.createServer()chatServer.on('connection',function(client){client.write('connection~~~\n')client.end()})chatServer.listen(2333)console.log('Server')

You can use the telnet command to access the server:






Step 2: Listen to all connection requests

Server Source Code:

var net = require('net')var chatServer = net.createServer()chatServer.on('connection',function(client){client.write('Hello~~\n')client.on('data',function(data){console.log(data);})})chatServer.listen(2333)console.log('Server')

An event listener client. on () is added. This function is called whenever the client sends data. Therefore, no matter what data is sent, the server displays the following information:


But there is a problem here: the returned content is garbled, because JS cannot process binary data very well, so Node adds a buffer library to help the server.

The printed characters are actually hexadecimal bytes, which can be in binary format, because both TCP and Telnet can process them.


Step 3: communication between clients:

Var net = require ('net') var chatServer = net. createServer () // server var clientList = [] // client array chatServer. on ('connection', function (client) {client. write ('Hello ~ Client ~ \ N') clientList. push (client) client. on ('data', function (data) {for (var I = 0; I <clientList. length; I ++) {clientList [I]. write (data) };})}) chatServer. listen (2333) console. log ('server ')

This is the simplest chat server. You can open multiple terminals and enter telnet localhost 2333 to access the server.



Next, improve the message sending and display methods to make the page more friendly.





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.