Building TCP Client
Hello All,
TCP is one of the most used transport protocols on the Internet, on top of which sit application protocols like HTTP. TCP is a connection-oriented protocol, which means that one endpoint requests and establishes a dedicated connection to another endpoint. This connection is a two-way dedicated stream into which both endpoints can send and receive data to/from each other at the same time. TCP guarantees that the messages you receive are in order. It has built-in mechanisms for flow control, making it a good platform for supporting machine-to-machine and human-to-machine protocols.
NOTE : One point you should keep in mind is that when you write to a TCP stream, you receive no acknowledgment that the other side has received the data. Even worse, because the underlying network implementation may chop and route your packets haphazardly, the other endpoint may have received only part of the message you sent (even though TCP internally tries to resend the packets that have been lost or corrupted). Remember that TCP guarantees only that the packets are received in order by the application, not that they are received at all. Furthermore, TCP is not message-oriented; it just provides a continuous stream of data. If you need to distinguish individual messages, you need to implement a framing protocol that specifies where each message starts and ends. HTTP, for instance, solves these problems whereby an application needs a request-response workflow from a server and request and response messages are clearly delimited.
CONNECTING TO A SERVER (TCP Client)
1 2 3 4 5 6 |
var net = require('net'); // Connect to TCP Server using the "net" module var portNumber = 8080; // portNumber of serever which you connect var hostName = "www.abc.com"; // its the hostName of your Server which is you want to connect // If absent, this hostName defaults to “localhost” var conn = net.createConnection(portNumber, hostName); // for Create Connection pass two argument host and port // to specify your server |
when the connection is established by passing a callback function as the last argument for notified Connected
1 2 3 4 5 |
function connectionListener(conn) { // connectionListener for notified Connection Established console.log('We have a new connection'); } // Like this : var conn = net.createConnection(portNumber, hostName, connectionListener); |
You can instead listen for the connect event emitted by the conn object:
1 |
conn.once('connect', connectionListener); |
SENDING AND RECEIVING DATA
The return value of the call to net.createConnection() is an instance of net.Socket , which represents the connection to the server and is both a readable and a writeable stream. It allow to send some Data
1 2 3 4 5 |
conn.write('here is a string for you!'); conn.write('Hey!', function() { console.log('data was written out'); }); //That the callback is not invoked when the server receives the data, // only when the data is written to the network. |
We can receive data from the server by listening to the data event emitted by the connection every time data is available:
1 2 3 4 |
conn.on('data', function(data) { console.log('some data has arrived:', data); }); conn.setEncoding('base64'); // you need to specify it by using setEncoding Buffers to Manipulate, Encode, and Decode Binary Data |
ENDING THE CONNECTION
we can close the connection from your endpoint by using the connection end method , you can also send some data (a buffer or a string)
1 2 3 4 5 6 7 8 9 10 |
conn.end(); // OR conn.end('Bye bye!', 'utf8'); //OR conn.write('Bye bye!', 'utf8'); conn.end(); |
HANDLING ERRORS
Errors can happen when you are trying to establish a connection — the hostname is not found on DNS, the target host is not reachable, or the connection is rejected — or a network error happens when you already had an established connection. You can trap errors by listening to the error event
1 2 3 |
conn.on('error', function(err) { console.error('this error happened:' + err.message + ', code: ' + err.code); }); |
Building TCP Client Example :
Save this code with File Name of client.js
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
var net = require('net'); var port = 8080; var host = 'localhost'; var conn = net.createConnection(port ,host); conn.on('connect', function() { console.log('connected to server'); conn.write('Hello Server'); }); conn.on('data' , function (){ console.log("Data received from the server: " , data); }); conn.on('error', function(err) { console.log('Error in connection:', err); }); conn.on('close', function() { console.log('connection got closed, will try to reconnect'); conn.end(); }); conn.on('end' , function(){ console.log('Requested an end to the TCP connection'); }); |
$ node client.js Run on Terminal
Save this code with File Name of server.js
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 |
var net = require('net'); var server = net.createServer(); var sockets = []; server.on('connection', function(socket) { console.log('got a new connection'); sockets.push(socket); socket.on('data', function(data) { console.log('got data:', data); sockets.forEach(function(otherSocket) { if (otherSocket !== socket) { otherSocket.write(data); } }); }); socket.on('close', function() { console.log('connection closed'); var index = sockets.indexOf(socket); sockets.splice(index, 1); }); }); server.on('error', function(err) { console.log('Server error:', err.message); }); server.on('close', function() { console.log('Server closed'); }); server.listen(8080); |
$ node server.js Run on Terminal
Thanks To All
For More Please See http://GoalKicker.com and http://www.it-ebooks.info
Recent Comments