Connection-Oriented Socket Tutorial
First steps
First you must create a Socket object. When you create this object, the socket is in an unconnected state; it is not associated with any host. In order for the socket to send and receive information, it must be bound to a host or destination and port.
Client Side
To create an outbound connection, use the ClientSocket function to bind your socket to a host and port. Client socket returns a boolean value, indicating if the connection was successful or not.
Example:
Socket my_sock;
int port=2000;
String host = "192.168.1.2";
if( ClientSocket(my_sock, port, host) )
{
my_sock.Write("hello world!");
my_sock.Close();
}
Server Side
Server side applications listen for incoming socket connections. A socket server listens and hands off connections to other individual sockets (usually separate threads).
To open a port to listen for incoming connections, you use the U++ ServerSocket function. ServerSocket() requires as input a socket object and the port to listen on.
Example:
Socket accept_socket, data_socket;
int port = 2000;
// Listen for connections using _accept_socket;
if( !ServerSocket(accept_socket, port) ){
throw Exc("Couldn't bind socket on the local port.");
}
// You can do this in a loop to accept many connections:
if( accept_socket.IsOpen() ){
dword ip_addr;
// Hand off successful connection to _data_socket
if( !accept_socket.IsError() && accept_socket.Accept(data_socket, &ip_addr) )
{
Cout() << "Connection from " << FormatIP(m_ipaddr) << "\n";
// Read from the socket until it is closed, has an error, or you see an end-of-file marker
// (EOF optional and application-specific)
while(data_socket.IsOpen() && !data_socket.IsEof() && !data_socket.IsError())
{
Cout() << data_socket.Read();
}
}
Cout() << "\n";
}
ServerSocket "binds" the socket to the port. You can then use the Socket object to read/write data.
So you can see the _accept_socket gets the connection and hands it off to _data_socket with the Accept() method. Then _data_socket has the connection.
Servers use this method with "Thread Pools" of socket connections to allow for a certain number of sockets to exist (usually 1 per thread).
|