Socket Programming in Java
Socket Programming in Java
Java
What is a Socket?
A socket is one end-point of a two-way communication link between two programs
running on the network.
It is through sockets that clients access the network and transmit data.
On the client-side: The client knows the hostname of the machine on which the server
is running and the port number on which the server is listening. To make a connection
request, the client attempts to contact the server on the given hostname and port.
The client also needs to give the server a way to contact it and so it binds to a local
port number that it will use during this connection. This is usually assigned by the
system. If everything goes well, the server accepts the connection. Upon acceptance,
the server binds a new socket with its remote endpoint set to the address and port of
the client and the same local endpoint. It also creates a new socket so that it can
continue to listen to the original port for connection requests while tending to the
needs of the newly-connected client.
Socket class
The Socket class
InetAddress class
It provides an abstract access to IP addresses.
No constructor, use static methods for creation
InetAddress getLocalHost() throws UnknownHostException;
InetAddress getByName(String host) throws UnknownHostException;
InetAddress[] getAllByName(String host) throws UnknownHostException;
Instance methods
byte[] getAddress();
String getHostName();
String getHostAddress();
boolean isMulticastAddress();
Sockets provided communication channel and support inter process communication in Java. For
example to communicate between two JVMs, sockets are used. Socket is an end point for
communication. There are two types of sockets.
UDP protocol is used in the connection less sockets communication. Also they are referred as datagram
communication protocol.
Each socket is indentified with following two numbers:
IP address
Port
Open Socket
Ports
InetAddress
InetAddress
InetAddress