Menu

TCPClient

Majenko Technologies

Connecting to a remote service using the TCPClient object is really simple.

First you need to create a new TCPClient object:

TCPClient mySocket;

Then add it to the networking stack:

Network.addPort(mySocket);

You can connect to a remote service with:

mySocket.connect(quad2ip(192,168,0,33), 10000);

and disconnect with:

mySocket.close();

The TCPClient object inherits the Print class, so you can use the standard .print() and .println() functions you are already familiar with:

mySocket.print("This is a test");

and

mySocket.println(analogRead(2),DEC);

Also, you have the read() function which returns a portion of the incoming buffer:

r = mySocket.read(buffer,len);

Where buffer is a pointer to an unsigned char buffer, and len is the maximum amount to read from the incoming queue. If there is less in that queue then it will return as much as possible. The actual number of bytes is returned by the function.

There is also a handy utility function readln() which operates just like read, but is blocking (it waits for input) and returns one entire line (terminated by a line feed) of data. Very useful for working with text based protocols like HTTP.

r = mySocket.readln(buffer,len);

The available() method tells you (just like for the Serial object) how many bytes are in the input buffer. You should use it to determine if there is anything to read before you perform a read:

if(mySocket.available()>0)
{
    r = mySocket.read(buffer,100);
}

Related

Wiki: TCPServer

Want the latest updates on software, tech news, and AI?
Get latest updates about software, tech news, and AI from SourceForge directly in your inbox once a month.