SoFunction
Updated on 2025-03-10

Example of chat function of nodejs simply implementing TCP server and client

This article describes the simple implementation of nodejs' chat function of TCP server and client. Share it for your reference, as follows:

Server side

var net = require('net');
var server = ();
//Aggregate all clientsvar sockets = [];
//Accept new client connection('connection', function(socket){
  ('got a new connection');
  (socket);
  //Read data from the connection  ('data', function(data){
    ('got data:', data);
    //Broadcast data    //Whenever a connected user enters data, the data will be broadcast to all other connected users    (function(otherSocket){
      if (otherSocket !== socket){
        (data);
      }
    });
    //Delete closed connection    ('close', function(){
      ('connection closed');
      var index = (socket);
      (index, 1);
    });
  });
});
('error', function(err){
  ('Server error:', );
});
('close', function(){
  ('Server closed');
});
(4000);

Client

var net = require('net');
var port = 4000;
var quitting = false;
var conn;
var retryTimeout = 3000;  //Three seconds, define three seconds and reconnect after re-connectionvar retriedTimes = 0;  //Record the number of reconnectionsvar maxRetries = 10;  //Reconnect at most ten times(); //The stream accepts the user's keyboard input. This readable stream is in a pause state when initialized. Call the resume() method on the stream to restore the stream('data', function(data){
  if (().trim().toLowerCase() === 'quit'){
    quitting = true;
    ('quitting');
    ();
    ();
  } else {
    (data);
  }
});
// When connecting, set to connect up to ten times, and turn on the timer before connecting for three seconds.(function connect() {
  function reconnect() {
    if (retriedTimes >= maxRetries) {
      throw new Error('Max retries have been exceeded, I give up.');
    }
    retriedTimes +=1;
    setTimeout(connect, retryTimeout);
  }
  conn = (port);
  ('connect', function() {
    retriedTimes = 0;
    ('connect to server');
  });
  ('error', function(err) {
    ('Error in connection:', err);
  });
  ('close', function() {
    if(! quitting) {
      ('connection got closed, will try to reconnect');
      reconnect();
    }
  });
  //Print  (, {end: false});
})();

I hope this article will be helpful to everyone's nodejs programming.