Blog about Programming Languages & Coding

Blog about Programming Languages & Coding
Contents for Computer Science, IT, B.Sc. CS & IT, M.Sc. CS & IT, MCA, BE CS & IT, ME CS & IT , Interview Questions, Books and Online Course Recommendations from Udemy, Coursera, etc

Networking in Java(Socket Programming)

 Networking in Java(Socket Programming)

Introduction

In Java, networking is performed using Transmission Control Protocol/Internet Protocol (TCP/IP) or the User Datagram Protocol (UDP).

Java provides a low-level control on the connection, allowing you to customize it according to your requirements. The package containing networking classes, called java.net, is shipped as part of the Java Development Kit (JDK). In Java, TCP connections are established using sockets and server sockets. These connections allow you to send and receive data to a Web Site. On the other hand, broadcast messages known as datagrams use the UDP. Datagram’s are encapsulated in a datagram packet and sent using a datagram socket. URLs can be created and modified using the URL class methods of Java.

Client-server architecture can be considered as a network environment that exchanges information between a server machine and a client machine where server has some resources that can be shared by different clients.

Overview of Socket and ports

Sockets are just like an end-point of two-way communication, which allow applications to communicate using network hardware and operating systems. However in case of java never get confused with a socket. Socket classes are used to establish a connection between client program and a server program. In java there is a java.net package, which provides two types of classes- first is ordinary socket, which implement the client side connection and second is server socket, which implement the server side connection.

The main purpose of the server socket is to listen an incoming connection request and ordinary socket is used to ask to server for the connection. Once a connection between client and server established, both the connected socket can communicate with each other.  

A socket forms the interface between the protocol and client for communication. A Java socket forms the base for data transmission between two computers using TCP/IP. The socket specifies the site address and the connection port. When packets reach a client or server, they are routed to the destination port specified in packet header.

In other hand we can consider the work of port in connection-based communication is like a medium through which, an application establish a connection with another application by binding a socket by a port number. Addressing the information and the port no., accompanied the data transfer over the network. The Ports are used by TCP and UDP to deliver the data to the right application, are identified by a 16-bit number.

Ports are typically used to map data to a particular process running on a client. If we consider a letter (data packet) sent to a particular apartment (IP) with house no. (port no), at this time the port no. is the most important part for the delivery of the letter. In order for the delivery to work, the sender needs to include a house number along with the address to ensure the letter gets to the right destination. 

If we consider the client-server architecture, a server application binds a socket to a specific port number in connection-based communication. It registered the server with the system where all the data destined for that port.

There are some ports which are predefine and called reserved ports. Some of them are given below :-

Reserved port numbers.

Service

Port no.

echo

7

daytime

13

ftp

21

telnet

23

smtp

25

finger

79

http

80

pop3

110

       
If we consider the range of the port numbers, there are 0 to 65,535 ports available. The port numbers ranging from 0 - 1023 are reserved ports or we can say that are restricted ports. All the 0 to 1023 ports are reserved for use by well-known services such as FTP, telnet and http and other system services. These ports are called well-known ports.

The java.net package

The java.net package contains the classes and interfaces required for networking. Some important classes are MulticastSocket, ContentHandler, URLServerSocket, Socket, InetAddress, URLConnection, DatagramSocket, and DatagramPacket. Some important interfaces in the java.net package are ContentHandlerFactory, SocketImplFactory, FileNameMap, URLStreamHandlerFactory, and SocketOptions.

InetAddress

This class encapsulates the numerical IP address and the domain name  for the address. Factory methods of a class allow you to call the method without referencing the object. The factory methods of this class are:

•        getLocalHost() method: Returns the name of the local computer

•        getByName() method: Returns the address by the Domain name

•        getAllByName() method: Returns all the addresses by their domain name

The instance methods of a class are methods that can be called from an object only. The instance methods for the class are:

•        getAddress() method: Returns a four-element byte array that represents the object’s IP address in network byte order

•        getHostAddress() method: Returns the host address

•        getHostName() method: Returns the hostname that is associated with the host address.

import java.net.*;

public class InetDemo

{

          public static void main(String[] args)

          {

                   try

                   {       

                             InetAddress inet =InetAddress.getByName("sun.com");

System.out.println("HostName=" + inet.getHostName()+"\n"+ inet.getHostAddress());

                     }

                   catch (UnknownHostException uhe)

                   {

                         uhe.printStackTrace();

                   }        }   }

The TCP/IP Server Socket

 

ServerSockets are quite different from normal Sockets. The main work of ServerSocket class is to wait for a request of connection by the client and connect them on published ports and then possibly returns a result to the requester.

 

The TCP/IP server socket creates a socket that listens for incoming connections. The server socket is implemented by creating an instance of the ServerSocket class. The server socket creates a server on the system to detect client connections.

 Constructors to Create TCP Server Sockets

An instance of the ServerSocket class can create a server that accepts incoming requests. An object of the ServerSocket class can be created using any one of these methods:

•        Specify the port number in the int type. An example of this method is:

 

                          ServerSocket(int port1)

 

Where, port1 is an integer, which can have any value between 0 and 65,536.

•        Specify the port number and maxQueue. maxQueue refers to the number of connections the socket can leave pending before refusing more connections.

An example of this method is:

 

                    ServerSocket(int port1, int maxQ)

 

Where, maxQ refers to an int value that specifies the number of connections it can leave pending before refusing any more connections.

•        Specify the port number, maxQueue, and the local address. An example of this method is:

 

ServerSocket(int port1, int maxQ, InetAddress address1)

Where, address1 refers to the IP address of the server on which the socket is created.

 

Methods of the ServerSocket Class

Socket accept() -- Accepts an incoming connection.

int getLocalPort() -- Returns the port number on which the server socket is listening.

void close() -- Closes the server socket.

 

import java.io.*;

import java.net.*;

public class SerSocket

{

          public static void main(String args[])

          {

                   int port=1080;

                   try

                   {

                             ServerSocket ss = new ServerSocket(port);

                             System.out.println("Server initialized on port " + port);

 

 

                             ss.getLocalPort();

                             {

                                      while(true)

                                                ss.accept();

                             }

                   }

                   catch (SocketException e)

                   {                           System.out.println("Socket error");          }

                   catch ( IOException e)

                   {                           System.out.println("An I/O Exception Occurred!");}

          }}

 

TCP/IP Client Socket

A TCP/IP client socket is used to create a reliable, bi-directional, stream-based connection between two computers on a network. The client socket is implemented by creating an instance of the Socket class. It is designed to connect to the server and initialize protocol exchanges.

Methods to Create TCP Client Sockets

An object of the Socket class can be created by these methods:

•        By specifying the hostname and port number as follows:

                        Socket (String hostname1, int port1)

Where, hostname1 is a string type variable that refers to the destination address and port1 refers to the port number of the destination address. This method can throw the exceptions, UnknownHostException or IOException, in case of errors.

•        By specifying an object of InetAddress and the port number as follows:

                            Socket(InetAddress ipaddr1, int port1)

Where, ipaddr1 is object of the InetAddress class and port1 refers to the port number of the destination. This method can throw the exception IOException, in case of errors.

Methods of the Socket Class

InetAddress getInetAddress() -- Returns the InetAddress that is associated with the socket object.

int getPort() -- Returns the port number on which the socket is connected

int getLocalPort() -- Returns the local port number on which the socket is created

InputStream getInputStream() -- Returns the InputStream associated with the calling object(InputStream allows reception of data from the other party)

OutputStream getOutputStream() -- Returns the OutputStream associated with the calling object(OutputStream allows dispatch of data to the other party)

void close() -- Closes the InputStream() and OutputStream() of the socket.

import java.io.*;

import java.net.*;

public class SocketDemo

{

          public static void main(String args[]) throws UnknownHostException

          {

                   try

                   {

                             Socket s = new Socket("www.gmail.com",80);

                             System.out.println("Connection to: " + s.getInetAddress());

                             System.out.println("Port Number: " + s.getPort());

                             System.out.println("Local Address: " + s.getLocalAddress());

                             System.out.println("Local Port: " + s.getLocalPort());

                   }

                   catch (UnknownHostException e)

                   {                           System.out.println("Site not found!");                }

                   catch (SocketException e)

                   {                           System.out.println("Socket error");          }

                   catch ( IOException e)

                   {                           System.out.println("An I/O Exception Occurred!");}

 

          }}

 

//Program where client sends number and server check whether number is +ve, -ve or zero

ServerDemoNo.java

import java.io.*;

import java.net.*;

class ServerDemoNo

{

          public static void main(String a[]) throws IOException

          {

                   BufferedReader br;

                   Socket s;

                   ServerSocket ss=new ServerSocket(5678);

                   while(true)    

                   {

                             s=ss.accept();

                             System.out.println("Connection Established!!");

                   br=new BufferedReader(new InputStreamReader(s.getInputStream()));

                             String msg=br.readLine();

                             int n=Integer.parseInt(msg);

 

                             PrintStream ps=new PrintStream(s.getOutputStream());

                             String st;

                             if(n<0)

                             {

                                      st=n+" is -ve";

                                      ps.println(st);

                             }

                             else if(n>0)

                             {

                                      st=n+" is +ve";

                                      ps.println(st);

                             }

                             else

                                      ps.println("Zero");

                  

                             s.close();

 

                   }        }}

import java.io.*;

import java.net.*;

class ClientDemoNo

{

          public static void main(String a[]) throws IOException

          {

                   Socket s=new Socket("127.0.0.1",5678);

                   System.out.println("Enter any no:");

          BufferedReader br=new BufferedReader(new InputStreamReader(System.in));

                   String no=br.readLine();

                   PrintStream ps=new PrintStream(s.getOutputStream());

                   ps.println(no);

 

BufferedReader br1=new BufferedReader(new InputStreamReader(s.getInputStream()));

                             String msg=br1.readLine();

System.out.println(msg);

                   ps.flush();

                   s.close();

                   }}

 

 

Networking in Java(Socket Programming) Networking in Java(Socket Programming) Reviewed by Asst. Prof. Sunita Rai, Computer Sci.. Dept., G.N. Khalsa College, Mumbai on January 13, 2022 Rating: 5

No comments:

Powered by Blogger.