Server Socket Programming

Introduction

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.

Packages

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:

import java.lang.Object.*;
import.net.ServerSocket.*;

Syntax

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.

Constructors

  • 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.

Methods

Some of the methods of the ServerSocket class are as follows:

MethodDescription
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.

Leave a comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.