TcpIp library
Provides functionality for TCP-IP communication. This library provides only client functionality.
This library can be initialized
var Tcpip = require('tcpip');
Create TcpIp instantion
Tcpip new Tcpip();
Constructor creates new instance of Tcpip object. For one TCP-IP socket (connection) you need one instance.
Open Tcp-ip connection
open (url, [callback(err)]);
String url - contains url include port number of target destination. For example misha.alarex.net:3001
Function callback - this function will be invoked after opening connection. Parameter err can contain error message.
ERROR_CODE_ALL_OK - everything is ok
ERROR_CODE_CONNECTION_NOT_FOUND - problem with server connection
ERROR_CODE_INVALID_PARAMETERS - bad parameters in URL
ERROR_CODE_IO_EXCEPTION - socket was broken during connection
ERROR_CODE_UNKNOWN_ERROR - something is wrong but nobody know what
Set Tcp-ip options
setOption(option, value);
Number option - option can be select from constants Number value - value for option
Return error code.
Options:
SOCKET_OPTION_DELAY - Socket option for the small buffer writing delay. Set to zero to disable Nagle algorithm for small buffer operations. Set to a non-zero value to enable.
SOCKET_OPTION_KEEPALIVE - Socket option for the keep alive feature. Setting KEEPALIVE to zero will disable the feature. Setting KEEPALIVE to a non-zero value will enable the feature.
SOCKET_OPTION_LINGER - Socket option for the linger time to wait in seconds before closing a connection with pending data output. Setting the linger time to zero disables the linger wait interval.
SOCKET_OPTION_RCVBUF - Socket option for the size of the receiving buffer.
SOCKET_OPTION_SNDBUF - Socket option for the size of the sending buffer.
Send data
send(data[,callback(error_code)]);
Function sends any data into socket.
String|ByteBuffer|Array|File data - data which be sent
Function callback - function will be invoked after data sending.
Number error_code
mysock.send(data, function(error_code){
if (code==mysock.ERROR_CODE_ALL_OK) {
.....
}
});
Close
close()
Function closes socket and release all resources.
Receiving data
receivedData(error_code, data)
Number error_code
ByteBuffer data - received data
Function will be invoked when data is incoming.
TCPIP example
var sys = require('system');
var Tcpip = require('tcpip');
var conn = new Tcpip();
conn.receivedData = function(errCode, data){
sys.println("Incoming event - err:"+errCode);
sys.println("Data length:"+data.getSize());
conn.close();
}
sys.println("Trying to open socket");
conn.open("time.nist.gov:13", function(err){
conn.setOption(conn.SOCKET_OPTION_KEEPALIVE,1);
sys.println("Trying to send data");
conn.send("\r\n\r\n",function(err){
sys.println("err:"+err);
});
});