Questions And Answers

More Tutorials

NodeJS TCP Sockets

A simple TCP server

// Include Nodejs' net module.
const Net = require('net');
// The port on which the server is listening.
const port = 8080;
// Use net.createServer() in your code. This is just for illustration purpose.
// Create a new TCP server.
const server = new Net.Server();
// The server listens to a socket for a client to make a connection request.
// Think of a socket as an end point.
server.listen(port, function() {
 console.log(`Server listening for connection requests on socket localhost:${port}`.);
// When a client requests a connection with the server, the server creates a new
// socket dedicated to that client.
server.on('connection', function(socket) {
 console.log('A new connection has been established.');
 // Now that a TCP connection has been established, the server can send data to
 // the client by writing to its socket.
 socket.write('Hello, client.');
 // The server can also receive data from the client by reading from its socket.
 socket.on('data', function(chunk) {
 console.log(`Data received from client: ${chunk.toString()`.});
 // When the client requests to end the TCP connection with the server, the server
 // ends the connection.
 socket.on('end', function() {
 console.log('Closing connection with the client');
 // Don't forget to catch error, for your own sake.
 socket.on('error', function(err) {
 console.log(`Error: ${err}`);


In this page (written and validated by ) you learned about NodeJS TCP Sockets . What's Next? If you are interested in completing NodeJS tutorial, your next topic will be learning about: NodeJS Hack.

Incorrect info or code snippet? We take very seriously the accuracy of the information provided on our website. We also make sure to test all snippets and examples provided for each section. If you find any incorrect information, please send us an email about the issue:

Share On:

Mockstacks was launched to help beginners learn programming languages; the site is optimized with no Ads as, Ads might slow down the performance. We also don't track any personal information; we also don't collect any kind of data unless the user provided us a corrected information. Almost all examples have been tested. Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness of all content. By using, you agree to have read and accepted our terms of use, cookies and privacy policy.