Java Network Programming (Socket Programming in Java)

JAVA NETWORK

Network programming is used to execute programs across multiple machines that are connected by a network.

The java.net package contains a collection of classes and interfaces that provide this functionality.

 

The java.net package provides support for the two common network protocols:

  • TCP – TCP (Transmission Control Protocol) is for reliable communication between two applications. It is used over the Internet protocol, known as TCP/IP.
  • UDP – (User Datagram Protocol) is a connectionless protocol that is used to transmit data packets between applications.

 

The socket provides the way to communicate between two computers using TCP. The client creates a socket on its end and support for the two common network protocols:

  • TCP – TCP (Transmission Control Protocol) is for reliable communication between two applications. It is used over the Internet protocol, known as TCP/IP.
  • UDP – (User Datagram Protocol) is a connectionless protocol that is used to transmit data packets between applications to connect that socket to a server.

 

There are two types of TCP socket present in Java: server and clients.

The server socket class acts as a listener which waits for clients to connect.

The client’s socket class is for clients. It initiates the exchange protocol and connects to the server.

The creation of socket object implicitly establishes a connection between the client and server.

 

Constructors client sockets

Socket(String hostName, int port) throws UnknownHostException, IOException

It creates a socket connected to the named host and port.

Socket(InetAddress ipAddress, int port) throws IOException

It creates a socket using a preexisting InetAddress object and a port.

Useful Methods

Modifier and Type

Method

Description

InetAddress

getInetAddress( )

It returns the InetAddress associated with the Socket object. It returns null if the socket is not connected.

int

getPort( )

It returns the remote port to which the invoking Socket object is connected. It returns 0 if the socket is not connected.

int

getLocalPort( )

It returns the local port to which the invoking Socket object is bound. It returns –1 if the socket is not bound.

Modifier and Type

Method

Description

InputStream

getInputStream( )

throws IOException

It returns the InputStream associated with the invoking socket.

OutputStream

GetOutputStream( )

throws IOException

It returns the OutputStream associated with the invoking socket.

We can gain access to the input and output streams associated with a Socket by using getInputStream( ) and getOuptutStream( ) methods. These methods can throw an IOException if the socket has been invalidated by a lost connection.

Java Socket Programming Example

This is the client class.

This is a server class.

Output:

Leave a Comment