Nodejs Implementing a Socket service

Source: Internet
Author: User
Tags socket error

Nodejs Implementing a socket service  What is a socket1. Socket allows a process he communicates with another process through an IP address and port, which is useful when you implement inter-process communication between two different processes running on the same server or access a service running on a completely different server. Node provides a net module that allows you to create both a socket server and a client that can connect to a socket server. 2. Sockets are located under the HTTP layer and provide point-to-point communication between servers. Sockets use socket addresses to work, which is a combination of IP addresses and ports. In a socket connection, there are two types of points: one is the server, it listens to the connection, and the other is the client, which opens a connection to the server. Both the server and the client require a unique combination of IP addresses and ports. 3. Sockets are the underlying structure of the HTTP module, and if you do not need to process Web requests such as Get and post, you only need to transfer data to points, then using sockets can provide you with a lightweight solution and more control.                          ,         &NB Sp                          ,         &NB Sp                          ,         &NB Sp                          ,         &NB Sp                          ,         &NB Sp                          ,         &NB Sp                          ,         &NB Sp                                                            ,         &N Bsp                          ,         &NB Sp                          ,         &NB Sp                         two  Net. Socket Object1.Socket objects are created on both the socket server and the client socket and allow data to be written and read back and forth between them. In the socket client, when you call Net.connect () or net.createconnection (), the socket object is created internally, and this object is meant to represent a socket connection to the server. Use the socket object to monitor the connection, send the data to the server, and process the response from the server.      On a socket server, when a client connects to a server, the socket object is created and passed to the connection event handler, which is intended to represent a socket connection to the client. In Nodejs, there are three kinds of Socket:tcp,udp,unix domain sockets, which mainly introduce the basic programming knowledge of TCP in Nodejs. 2. To create a socket object, you can use the following methods:
//the first method, through an options parametervarSocketclient =net.connect (options, [Connectionlistener]);varSocketclient =net.createconnection (options, [Connectionlistener]);//The second method, by accepting the port and host values as direct parametersvarSocketclient =Net.connect (port, [host], [Connectionlistener]);varSocketclient =net.createconnection (port, [host], [Connectionlistener]);//The third method, by accepting the path parameter for the specified file system location, is used by a UNIX socket when creating the socket object. varSocketclient =net.connect (path, [Connectionlistener]);varsocketclient = net.createconnection (path, [Connectionlistener]);
whichever you use, it will return a socket object, the only difference being the first parameter that is accepted, and the last parameter is the callback function that executes when the connection is opened to the server. and whether you use Net.connect or net.createconncetion, they work exactly the same way. so as for the first parameter, the options specified are:Port: The ports that the client should connect to. This option is required. Host: The domain name or IP address of the server to which the client should connect. Default to localhostlocaladdress: The local IP address that the client should bind to for the network connection. Allowhalfopen: A Boolean value that, if true, indicates that when a fin packet is sent from the other end of the socket, the socket will not automatically send a FIN packet, leaving half of the duplex stream open. Default is False 3. Once the socket object is created, it provides several events that are emitted during the lifetime of the connection to the server, as follows:Connect: Issued when a connection to the server is successfully established. callback function does not accept any argumentsdata: Emitted when a socket is received. If no data time handlers are connected, the data may be lost. The callback function must accept a buffer object as a parameter that contains a block of data read from the socket. end: Emitted when the server terminates the connection by sending a fin. callback function does not accept any argumentstimeout: Due to inactivity, the connection to the server is issued at times of timeout. drain: Emitted when the write buffer becomes empty. You can use this event to truncate the data stream that is written into the socket. callback function does not accept any argumentsError : emitted on socket connection. The callback function should accept the unique parameters of the error. Close: Issued when the socket is closed completely, it may have been closed by an end () method, or it has been closed because of an error. callback function does not accept any arguments The 5.Socket object also provides several properties that can be accessed to obtain information about the object:buffersize The number of bytes in the stream that is currently buffered and waiting to be written to the socketremoteaddress socket connection to the IP address of the remote serverRemotePort socket connection to the port of the remote serverlocaladdress The local IP address of the remote client for the socket connectionLocalPort Local port used by remote clients for socket connectionsbyteread number of bytes read by socketbytewritten number of bytes written by socketsthree net. Server Objectyou can use net. The server object creates a TCP socket server and listens for connections to it, and you will be able to read and write data. to create a server exclusive, use the Net.createserver () method:Net.createserver ([Options],[connectlistener])where options is an object that specifies the option to use when creating a socket server object, such as Allowhalfopen, to keep half of the duplex stream open and default to False. Connectllistener is the callback function for the connection event, which is executed when the connection is received. Example:
varNET = require (' net ');varHOST = ' 127.0.0.1 ';varPORT = 6969; //Create a TCP server instance, call the Listen function to start listening on the specified port//The callback function that passed in Net.createserver () will act as a handler for the "Connection" event//in each "connection" event, the socket object received by the callback function is uniqueNet.createserver (function(sock) {//we get a connection-the connection automatically associates a socket objectConsole.log (' CONNECTED: ' + sock.remoteaddress + ': ' +sock.remoteport); //Add a "data" event handler for this socket instanceSock.on (' Data ',function(data) {Console.log (' DATA ' + sock.remoteaddress + ': ' +data); //When the data is sent back, the client receives data from the serverSock.write (' you said ' + Data + ' "'));     }); //add a "Close" event handler for this socket instanceSock.on (' Close ',function(data) {Console.log (' CLOSED: ' +sock.remoteaddress+ ' +sock.remoteport); }); }). Listen (PORT, HOST); Console.log (' Server listening on ' + HOST + ': ' + PORT ';
The server can also accept TCP connections in a slightly different way, which is to explicitly handle the "connection" event:
var server = net.createserver (); Server.listen (PORT, HOST); Console.log (' Server listening on ' +      + ': ' + server.address (). Port); Server.on (function(sock) {    console.log (         ' CONNECTED: ' + + ': ' +  Sock.remoteport);     // the other content is the same as in the preceding section });
The above two examples are written in different ways, and there is no essential difference. Create a TCP client now let's create a TCP client to connect to the server you just created, which sends a bunch of messages to the server and closes the connection after getting feedback from the server. The following code describes the process.
varNET = require (' net ');varHOST = ' 127.0.0.1 ';varPORT = 6969; varClient =NewNet. Socket (); Client.connect (PORT, HOST,function() {Console.log (' CONNECTED to: ' + HOST + ': ' +PORT); //send data to the server immediately after the connection is established and the server will receive the dataClient.write (' I am Chuck norris! ');}); //adding the "Data" event handler to the client//data is what the server sends backClient.on (' Data ',function(data) {Console.log (' DATA: ' +data); //Close the connection completelyClient.destroy ();}); //add a "Close" event handler to the clientClient.on (' Close ',function() {Console.log (' Connection closed ');});

Let me give you an example:
varNet=require (' Net ');functiongetconnection (connname) {varClient=net.connect ({port:8017,host: ' 127.0.0.1 '},function() {Console.log (Connname+ ' Connected: '); Console.log (' Local=%s:%s ', This. LocalAddress, This. LocalPort); Console.log (' Remote=%s:%s ', This. remoteaddress, This. RemotePort);  This. SetTimeout (500);  This. setencoding (' UTF8 ');  This. On (' Data ',function(data) {Console.log (Connname+ ' from Server: ' +data.tostring ());  This. end ();        });  This. On (' End ',function() {Console.log (Connname+ ' Client disnected ');        });  This. On (' Error ',function(Err) {Console.log (' Socket Error: ', Json.stringify (err));        });  This. On (' timeout ',function() {Console.log (' Socket Time Out ');        });  This. On (' Close ',function() {Console.log (' Socket Closed ');    });    }); returnclient;}functionWriteData (socket,data) {varsuccess=!socket.write (data); if(!success) {        (function(socket,data) {socket.once (' Drain ',function() {writedata (socket,data);        });    }) (Socket,data); }}varExample1=getconnection (' example1 ');varExample2=getconnection (' example2 '); WriteData (example1,' This is example1 '); WriteData (Example2,' This is example2 '); varServer=net.createserver (function(client) {Console.log (' Client connection: '); Console.log (' local=%s:%s ', Client.localaddress,client.localport); Console.log (' remote=%s:%s ', Client.remoteaddress,client.remoteport); Client.settimeout (500); Client.setencoding (' UTF8 '); Client.on (' Data ',function(data) {Console.log (' Received data from client on port%d:%s ', client.remoteport,data.tostring ()); Console.log (' Bytes Received: ' +data.tostring ()); WriteData (Client,' Sending: ' +data.tostring ()); Console.log (' Bytes Sent: ' +Client.byteswritten)}); Client.on (' End ',function() {Console.log (' Client disconnected '); Server.getconnections (function(Err,count) {Console.log (' Remaining Connections: ' +count);    });    }); Client.on (' Error ',function(Err) {Console.log (' Socket Error: ' +json.stringify (err));    }); Client.on (' Timeout ',function() {Console.log (' Socket Time Out '); });}); Server.listen (8017,function() {Console.log (' Server listening: ' +json.stringify (Server.address ())); Server.on (' Close ',function() {Console.log (' Server Terminated ');    }); Server.on (' Error ',function(Err) {Console.log (' Server Error: ', Json.stringify (err)); });});

Nodejs Implementing a Socket service

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.