TcpSocket
Read/Write to/from a Tcp Socket.
Internally, two threads are started to handle the communication with the remote host.
class TcpSocket {
constructor TcpSocket('a name');
bool open( String host, int port );
bool close();
bool isConnected();
bool hasData();
bool writeSocket( string );
string readSocket();
}
Constructor
- Objet: TcpSocket('name')
var p = new TcpSocket('test');
.open
.open( String host , int port)
Throws an exception if the connection cannot be established.
var msg = 'test' ;
var sock = new TcpSocket('G5500');
try {
sock.open('127.0',4533);
sock.writeSocket (msg + "\n");
sock.close();
}
catch (err) {
print('Error: ' + err);
}
Will throw TcpSocket::open() Connection to 127.0 refused
.close
Close the active connection
.close();
.isConnected
Returns true if the socket is connected, false otherwise
.hasData
.hasData();
.writeSocket
.writeSocket( string );
.readSocket
Retrieve serial buffer into text object
.readSocket();
.readBytes
Retrieve buffer into Uint8Array object
.readBytes();
.readInt16
Retrieve buffer into Uint16Array object
.readInt16();
Example 1
var s = new TcpSocket('test');
if( s.open('stackoverflow.com', 80) == false ) {
print('Cannot open socket') ;
exit();
}
print('Sending request');
s.writeSocket('GET /questions HTTP/1.0\n');
s.writeSocket('Host: stackoverflow.com\n');
s.writeSocket('\n\n');
sleep(100);
print('Reading response');
while( s.hasData() ) {
var rep = s.readSocket();
print('reply:' + rep );
}
print('Closing');
s.close();
Example 2
- Send TCP frames to TCP listener (use
nc -l -p 4533
on another shell session).
var sock = new TcpSocket('mytcp');
sock.open('127.0.0.1',4533);
for (var a=0; a<200; a++) {
if (sock.isConnected()) {
sock.writeSocket (a + "\n");
print(a,' -- Connected : ',sock.isConnected());
sleep(150);
} else {
sleep(200);
print(a,' -- Connected : ',sock.isConnected());
sock.open('127.0.0.1',4533);
}
}
Last update: November 21, 2023