socket function call.
This call looks like this:
int s = socket(domain, type of service, protocol)
There are 5 types of sockets:
BSD sockets provides a single interface to all domains in terms of addressing. This is confusing and error prone! The basic type is the sockaddr structure given below.
struct sockaddr {
u_short sa_family;
char sa_data[14];
};
For the UNIX domain, the addressing structure is the following.
struct sockaddr_un {
u_short sun_family; /* set to AF_UNIX */
char sun_path[108]; /* Pathname */
};
For the Internet domain, the addressing structure is the following.
struct in_addr {
u_long s_addr;
};
struct sockaddr_in {
u_short sin_family; /* set to AF_INET */
u_short sin_port; /* Port number */
strut in_addr sin_addr; /* IP address */
char sin_zero[8]; /* padding, not used */
};
The sequence of BSD socket calls is based on the type of transport
and the type of role the application desires to play. For TCP, the
client typically executes the following functions.
socket()
bind() - optional
connect()
send()/recv() - service processing
close()
The process where by the client connects to a server is sometimes referred
to as an "active open" operation.For TCP, the server typically executes the following functions.
socket()
bind()
listen()
accept()
send()/recv() - service processing
close()
The process where by the server does the listen and accept steps is
sometimes referred to as a "passive open" operation.For UDP, the client and server are almost identical and typically execute the following functions.
socket()
bind() - optional for client
sendto()/recvfrom() - service processing
close()
[Echo Client and Server code examples]
Internet Addresses
Internet addresses (both IP address and port) are encapsulated into
a single object. This object hides the DNS lookup and some other
details. This object is the InetAddress class.
DatagramPacket class. Each instance of this class
will have a destination InetAddress and its data contents.
Each DatagramPacket is sent using a "machine" abstraction
for sending datagrams. This is the DatagramSocket class.
The only difference between clients and servers is that the
DatagramSocket has a constructor with an optional
PORT argument.
InputStream object and an
output stream, a Java OutputStream. This class is the
Socket class. This abstraction is used for the
client and server ends of a connection.
Servers in Java have an additional ServerSocket
object that is used for accepting connections from clients.
The accept method of this class accepts connections and creates
Socket objects.
[Echo Client and Server code examples for Java]