This is an example to show how to use ArSocket to create a client and a server. This is the client program. The server is socketServerExample.cpp.
This connects to a server on the host 'localhost' on port 7777. It waits for the server to say hello, then it says hello in reponse. It then closes the socket and exits.
First run the server program socketServerExample. Then run this client program on the same computer, perhaps in a different terminal window. You should see the server accept the connection, send its greeting to this client program, and see this client respond with its greeting text to the server.
socketServerExample.cpp
00001 #include "Aria.h" 00002 00003 00029 int main() 00030 { 00031 // The string to send to the server. 00032 char *strToSend="Hello Server"; 00033 // The buffer in which to recieve the hello from the server 00034 char buff[100]; 00035 // The size of the string the server sent 00036 size_t strSize; 00037 00038 // The socket object 00039 ArSocket sock; 00040 00041 // Initialize Aria. It is especially important to do 00042 // this on Windows, because it will initialize Window's 00043 // sockets system. 00044 Aria::init(); 00045 00046 // Connect to the server 00047 ArLog::log(ArLog::Normal, "socketClientExample: Connecting to localhost TCP port 7777..."); 00048 if (sock.connect("localhost", 7777, ArSocket::TCP)) 00049 ArLog::log(ArLog::Normal, "socketClientExample: Connected to server at localhost TCP port 7777."); 00050 else 00051 { 00052 ArLog::log(ArLog::Terse, "socketClientExample: Error connecting to server at localhost TCP port 7777: %s", sock.getErrorStr().c_str()); 00053 return(-1); 00054 } 00055 00056 // Read data from the socket. read() will block until 00057 // data is received. 00058 strSize=sock.read(buff, sizeof(buff)); 00059 00060 // If the amount read is 0 or less, its an error condition. 00061 if (strSize > 0) 00062 { 00063 buff[strSize]='\0'; // Terminate the string with a NULL character: 00064 ArLog::log(ArLog::Normal, "socketClientExample: Server said: \"%s\"", buff); 00065 } 00066 else 00067 { 00068 ArLog::log(ArLog::Terse, "socketClientExample: Error in waiting/reading from the server."); 00069 return(-1); 00070 } 00071 00072 // Send the string 'Hello Server' to the server. write() should 00073 // return the same number of bytes that we told it to write. Otherwise, 00074 // its an error condition. 00075 if (sock.write(strToSend, strlen(strToSend)) == strlen(strToSend)) 00076 ArLog::log(ArLog::Normal, "socketClientExample: Said hello to the server."); 00077 else 00078 { 00079 ArLog::log(ArLog::Terse, "socketClientExample: Error sending hello string to the server."); 00080 return(-1); 00081 } 00082 00083 // Now close the connection to the server 00084 sock.close(); 00085 ArLog::log(ArLog::Normal, "socketClientExample: Socket to server closed."); 00086 00087 // Uninitialize Aria and exit 00088 Aria::uninit(); 00089 return(0); 00090 }
1.4.7