This example will show you how to use node js to implement TCP socket client-server communication. To achieve this you need to import node js built-in net module and use the net.createServer method to create a net.Server object as TCP server, and use net.createConnection method to create a net.Socket object as TCP client.
1. Node JS TCP Socket Client Server Example.
This example contains two source files, tcp_socket_server.js, and tcp_socket_client.js.
1.1 tcp_socket_server.js
// Import net module. var net = require('net'); // Create and return a net.Server object, the function will be invoked when client connect to this server. var server = net.createServer(function(client) { console.log('Client connect. Client local address : ' + client.localAddress + ':' + client.localPort + '. client remote address : ' + client.remoteAddress + ':' + client.remotePort); client.setEncoding('utf-8'); client.setTimeout(1000); // When receive client data. client.on('data', function (data) { // Print received client data and length. console.log('Receive client send data : ' + data + ', data size : ' + client.bytesRead); // Server send data back to client use client net.Socket object. client.end('Server received data : ' + data + ', send back to client data size : ' + client.bytesWritten); }); // When client send data complete. client.on('end', function () { console.log('Client disconnect.'); // Get current connections count. server.getConnections(function (err, count) { if(!err) { // Print current connection count in server console. console.log("There are %d connections now. ", count); }else { console.error(JSON.stringify(err)); } }); }); // When client timeout. client.on('timeout', function () { console.log('Client request time out. '); }) }); // Make the server a TCP server listening on port 9999. server.listen(9999, function () { // Get server address info. var serverInfo = server.address(); var serverInfoJson = JSON.stringify(serverInfo); console.log('TCP server listen on address : ' + serverInfoJson); server.on('close', function () { console.log('TCP server socket is closed.'); }); server.on('error', function (error) { console.error(JSON.stringify(error)); }); });
Below is the server-side output.
/usr/local/bin/node /Users/zhaosong/Documents/WorkSpace/dev2qa.com-example-code/JavaScriptExampleWorkspace/NodeJSWorkspace/SocketClientServer/tcp_socket_server.js TCP server listen on address : {"address":"::","family":"IPv6","port":9999} Client connect. Local address : ::ffff:127.0.0.1:9999. client remote address : ::ffff:127.0.0.1:51814 Client connect. Local address : ::ffff:127.0.0.1:9999. client remote address : ::ffff:127.0.0.1:51815 Receive client send data : Java is best programming language. , data size : 35 Receive client send data : Node is more better than java. , data size : 31 Client disconnect. There are 1 connections now. Client disconnect. There are 0 connections now.
1.2 tcp_socket_client.js
// Import net module. var net = require('net'); // This function create and return a net.Socket object to represent TCP client. function getConn(connName){ var option = { host:'localhost', port: 9999 } // Create TCP client. var client = net.createConnection(option, function () { console.log('Connection name : ' + connName); console.log('Connection local address : ' + client.localAddress + ":" + client.localPort); console.log('Connection remote address : ' + client.remoteAddress + ":" + client.remotePort); }); client.setTimeout(1000); client.setEncoding('utf8'); // When receive server send back data. client.on('data', function (data) { console.log('Server return data : ' + data); }); // When connection disconnected. client.on('end',function () { console.log('Client socket disconnect. '); }); client.on('timeout', function () { console.log('Client connection timeout. '); }); client.on('error', function (err) { console.error(JSON.stringify(err)); }); return client; } // Create a java client socket. var javaClient = getConn('Java'); // Create node client socket. var nodeClient = getConn('Node'); javaClient.write('Java is best programming language. '); nodeClient.write('Node is more better than java. ');
Below is the client-side output. We can see that there are two socket connections use different local ports number to connect to the same socket server.
/usr/local/bin/node /Users/zhaosong/Documents/WorkSpace/dev2qa.com-example-code/JavaScriptExampleWorkspace/NodeJSWorkspace/SocketClientServer/tcp_socket_client.js Connection name : Java Connection local address : 127.0.0.1:51814 Connection remote address : 127.0.0.1:9999 Connection name : Node Connection local address : 127.0.0.1:51815 Connection remote address : 127.0.0.1:9999 Server return data : Server received data : Java is best programming language. , send back to client data size : 0 Client socket disconnect. Server return data : Server received data : Node is more better than java. , send back to client data size : 0 Client socket disconnect. Process finished with exit code 0
2. Question & Answer.
2.1 How to make node js TCP socket server connection persistently.
- I use node js to implement a TCP socket server, it can receive data from the client request and send data back to the client. But after a client closes the previous connection to the socket server and reconnects to the socket server again, the server will create another process with a new PID to handle the request. This does not meet my needs. I want a persistent connection between the client and the socket server so that I can send request data and receive response data at any time. How can I implement this? Thanks.
2.2 How to get client request domain hostname when a client requests a Node.js TCP socket server.
- I create a very simple TCP socket server with the Node.js net module like below. It just listens on the 80 port number ( the HTTP default listening port number ), and when a connection comes in I want to display the client requested domain hostname, but it only returns the server IP address, so can anybody tell me how to get the client requested hostname in Node.js? Thanks.
// Create a TCP socket server with the Node.js net module. var server = net.createServer(function (socket) { socket.end("hello you are welcome to Node.js\n"); }); // The sever wil listen to 80 port number ( the default http port number). server.listen(80, function() { // Get server address. address = server.address(); // Print out the server address on console. console.log("Node.js TCP socket server listening on %j", address); }); // When a client connect to the server, the connection event will be triggered. Because we can point multiple domains to the same ip address, so I want to parsed out which domain this client request used to connect to this server. server.on('connection', function(socket) { // Log client requested hostname domain value. The below code are all not correct. log('Connect request hostname : ', socket.address()); log('Connect request hostname : ', socket.localAddress; });
- You can not get the client request hostname in the TCP layer, because the hostname value is only provided in the HTTP layer. There is a host header when the client requests to the server, and you can get its value through the code
req.headers['host']
.