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.