Tuesday, December 22, 2009

Socket Client Functions









Socket Client Functions


A client station wishing to connect to a server must also create a socket by calling the socket function. The next step is to connect with a server, and it is necessary to specify a port, host address, and other information. There is just one additional function, connect.


Connecting to a Server


If there is a server with a listening socket, the client connects with the connect function.



int connect (
SOCKET s,
LPSOCKADDR lpName,
int nNameLen);


Parameters

s is a socket created with the socket function.


lpName points to a sockaddr_in structure that has been initialized with the port and IP address of a system with a socket, bound to the specified port, that is in listening mode.


Initialize nNameLen with sizeof (struct sockaddr_in).


A return value of 0 indicates a successful connection, whereas SOCKET_ERROR indicates failure, possibly because there is no listening socket at the specified address.


The socket, s, does not need to be bound to a port before the connect call, although it can be. The system allocates a port if required and determines the protocol.


Example: Client Connecting to a Server


The following code sequence allows a client to connect to a server. Just two function calls are required, but the address structure must be initialized before the connect call. Error testing is omitted here but should be included in actual programs. In the example, it is assumed that the IP address (a text string such as "192.76.33.4") is given in argv [1] on the command line.



SOCKET ClientSock;
...
ClientSock = socket (AF_INET, SOCK_STREAM, 0);
memset (&ClientSAddr, 0, sizeof (ClientSAddr));
ClientSAddr.sin_family = AF_INET;
ClientSAddr.sin_addr.s_addr = inet_addr (argv [1]);
ClientSAddr.sin_port = htons (SERVER_PORT);
ConVal = connect (ClientSock,
(struct sockaddr *) &ClientSAddr,
sizeof (ClientSAddr));


Sending and Receiving Data


Socket programs exchange data using send and recv, which have nearly identical argument forms (the send buffer has the const modifier). Only send is shown here.



int send (
SOCKET s,
const char * lpBuffer,
int nBufferLen,
int nFlags);


The return value is the actual number of bytes transmitted. An error is indicated by the value SOCKET_ERROR.


nFlags can be used to indicate urgency (such as out-of-band data), and MSG_PEEK can be used to look at incoming data without reading it.


The most important fact to remember is that send and recv are not atomic, and there is no assurance that all the requested data has been received or sent. "Short sends" are extremely rare but possible, as are "short receives." There is no concept of a message as with named pipes; therefore, you need to test the return value and resend or transmit until all data has been transmitted.


You can also use ReadFile and WriteFile with sockets by casting the socket to a HANDLE in the function call.









    No comments: