Table of Contents
Sockets are the glue of network programs. These are the channels through which devices communicate with each other over a network. Every application has two components to a socket. One is the server-side of the socket and the other is the client-side. A client initiates communication through the socket. When the server accepts the request, communication is established and information transaction happens through the selected protocol.
The package that contains the server socket class is java.net. If you want to use a server-side socket, you will need to import the following to your program:
public class ServerSocket extends Object implements Closeable
This class implements the server socket. A request is sent to establish a link with the server socket. When it is established, the server performs the required action and sends back some data to the requester through the socket.
- ServerSocket() – Creates an unbound server socket
- ServerSocket (int port) – This will create a server socket associated with a particular port as mentioned in the parameter.
- ServerSocket(int port, int backlog) – Creates a socket with the mentioned port and backlog
- ServerSocket(int port, int backlog, InetAddress bindAddress) – Creates a new server socket with a specific port, listen backlog, an a local IP address to bind to.
Some of the methods of the ServerSocket class are as follows:
|Socket accept()||Tries to establish a connection with a suitable socket.|
|Void bind(SocketAddress endpoint)||Creates a connection of the server socket with a client socket to a specific IP address and port.|
|Void bind(Socket Address endpoint, int backlog)||Binds the server socket with an IP address and a backlog|
|Void close()||The socket is closed and the connection is broken.|
|serverSocketChannel getChannel()||Returns the unique ServerSocketChannel object|
|Int getLocalPort ()||Returns the port number the socket is associated to.|
|Boolean isBound()||Returns the binding state of the Server Socket.|