Programming with Rudiments using the inetsocketclient class
The inetsocketclient class provides methods for connecting to servers over inet (TCP/IP) sockets.
Here's the code for a client that can communicate with the inetsocketserver program. This client connects to a server, sends a string, reads what the server sends back, and prints it out.
The host, port, timeout, retry wait, and number of tries are all configurable.
#include <rudiments/inetsocketclient.h>
#include <rudiments/charstring.h>
#include <rudiments/stdio.h>
int main(int argc, const char **argv) {
// create a client and connect to a server
inetsocketclient client;
client.setHost("localhost");
client.setPort(8000);
client.setTimeoutSeconds(5);
client.setTimeoutMicroseconds(0);
client.setRetryWait(1);
client.setTries(3);
if (client.connect()!=RESULT_SUCCESS) {
stdoutput.write("failed to connect to localhost:8000\n");
return 1;
}
stdoutput.write("connected to localhost:8000\n");
// send a message to the server
const char *message="hello from the client";
client.write(message,charstring::getLength(message));
stdoutput.write("sent message\n");
// read the server's response
char buf[1024];
ssize_t bytesread=client.read(buf,sizeof(buf)-1);
if (bytesread>0) {
buf[bytesread]='\0';
stdoutput.printf("received: %s\n",buf);
}
// close the connection
client.close();
}
Inet sockets allow clients and servers to communicate across a network. Unix sockets can be used to allow clients and servers on the same machine to communicate. Though clients and servers on the same machine could communicate over an inet socket using localhost, unix sockets are much faster and use fewer system resources. See the unixsocketserver and unixsocketclient examples.