Java Network Programming (Socket Programming in Java)

tutorial and example
tutorial and example

JAVA NETWORK

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

The java.net package contains 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 the Internet protocol, known as TCP/IP.
  • UDP – (User Datagram Protocol) is a connectionless protocol that is used to transmit data packets between applications.

Socket provides the way to communicate between two computers using TCP. Client creates socket on its end and tries to connect that socket to a server.

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

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

The  clients socket class is for clients. It initiate exchange protocol and connect to server.

The creation of socket object implicitly establish 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 server class.

Output: