Internet chat rooms in net --- node.js server using TCP network module with the client

// 1. Create a simple net server 
// const net = The require ( "net"); 
// const Server = net.createServer ((c) => { 
//      // Connection listener 
//      console.log ( "Customer connected terminal "); 
//      c.on (" end ", () => { 
//          the console.log (" client disconnected "); 
//      }) 
//      c.write ( 'Hello \ R & lt \ n-'); 
//      c.pipe (C); 
// }) 
// server.on (' error ', (ERR) => { 
//      the throw ERR 
// }) 
// server.listen ( 8000, () => { 
//      console.log ( "server started.") 
// }) 
// 2. Nested Byte
// var server = require('net').createServer((socket) => {
//     console.log('new connection');
//     socket.setEncoding("UTF8");
//     socket.on('data', (data) => {
//         console.log('got:', data.toString());
//         if (data.trim().toLowerCase() === 'quit') {
//             socket.write('Bye!');
//             return socket.end();
//         } else {
//             socket.write(data + '----我已处理过的数据!\r\n')
//         }
//     })
//     socket.on("end", () => {
//         console.log ( "client disconnected"); 
//      }) 

// }) the listen (3000). 
// 3. Output bytes from the sleeve to the file 
// var WS = the require ( "FS"). createWriteStream ( 'output.txt'); 
// the require ( 'NET') the createServer (function (Socket) {. 
//      socket.pipe (WS); 
// }). the listen (4000) 
// 4. files from byte output to the client sets 
// the require ( "NET") the createServer (function (Socket) {. 
//      var RS = the require ( 'FS') createReadStream ( 'output.txt');. 
//      rs.pipe ( Socket) 
//    // rs.pipe (Socket, {End: to false}) 
// .}) the listen (4000) 
// . 5.TCP chat server 
var= the require NET ( "NET" );
 var Server = net.createServer ();
 var Sockets = [];    // 1. Save all connected 
server.on ( 'error', function (ERR) {
     the throw ERR 
}) 

// 1. Accept link 
server.on ( 'connection', function (Socket) { 
    the console.log ( 'A new new connection GOT' ); 
    sockets.push (Socket); // 2 save 
    @ 2 is read from the connection data 
    socket.setEncoding ( "the UTF8" ); 
    socket.on ( 'data', function (data) { 
        the console.log ( 'GOT data:', Data)
         // broadcast data broadcasting data to all connected 
        sockets.forEach ( function (otherSocket) {
             IF (otherSocket ==! Socket) { 
                otherSocket.write (Data); 
            } 
        }) 
    }) 
}) 
// . 3. when the connection is closed, he will remove 
server.on ( 'Close', function () { 
    the console.log ( 'Close Server' );
     var index = sockets.indexOf (Socket); 
    sockets.splice (index, . 1 ) 
}) 

server.listen ( '4000');

Start command: telnet 127.0.0.1 4000

 

 

Reference: https://www.cnblogs.com/jkko123/p/10247593.html

Guess you like

Origin www.cnblogs.com/lguow/p/11720759.html