CORE JAVA: Networking

Introduction

  • Java Networking is a concept of connecting two or more computing devices together so that we can share resources.
  • The term network programming refers to writing programs that execute across multiple devices (computers), in which the devices are all connected to each other using a network.
  • The java.net package of the J2SE APIs contains a collection of classes and interfaces that provide the low-level communication details, allowing you to write programs that focus on solving the problem at hand.
  • The java.net package provides support for the two common network protocols −
  1. TCP − TCP stands for Transmission Control Protocol, which allows for reliable communication between two applications. TCP is typically used over the Internet Protocol, which is referred to as TCP/IP.
  2. UDP − UDP stands for User Datagram Protocol, a connection-less protocol that allows for packets of data to be transmitted between applications.

Socket Programming

  • Sockets provide the communication mechanism between two computers using TCP. A client program creates a socket on its end of the communication and attempts to connect that socket to a server.
  • When the connection is made, the server creates a socket object on its end of the communication. The client and the server can now communicate by writing to and reading from the socket.
  • The java.net.Socket class represents a socket, and the java.net.ServerSocket class provides a mechanism for the server program to listen for clients and establish connections with them.
  • The following steps occur when establishing a TCP connection between two computers using sockets −
  1. The server instantiates a ServerSocket object, denoting which port number communication is to occur on.
  2. The server invokes the accept() method of the ServerSocket class. This method waits until a client connects to the server on the given port.
  3. After the server is waiting, a client instantiates a Socket object, specifying the server name and the port number to connect to.
  4. The constructor of the Socket class attempts to connect the client to the specified server and the port number. If communication is established, the client now has a Socket object capable of communicating with the server.
  5. On the server side, the accept() method returns a reference to a new socket on the server that is connected to the client’s socket.
  • After the connections are established, communication can occur using I/O streams. Each socket has both an OutputStream and an InputStream. The client’s OutputStream is connected to the server’s InputStream, and the client’s InputStream is connected to the server’s OutputStream.
  • TCP is a two-way communication protocol, hence data can be sent across both streams at the same time. Following are the useful classes providing complete set of methods to implement sockets.

Socket Class Methods:

The java.net.Socket class represents the socket that both the client and the server use to communicate with each other. The client obtains a Socket object by instantiating one, whereas the server obtains a Socket object from the return value of the accept() method.

The Socket class has five constructors that a client uses to connect to a server −

91.png


 Server Socket

  • Creating a ServerSocket
  • Listening For Incoming Connections
  • Closing Client Sockets
  • Closing Server Sockets
  • Creating a ServerSocket

Here is a simple code example that creates a ServerSocket that listens on port 9000:

ServerSocket serverSocket = new ServerSocket(9000);
  • Listening For Incoming Connections

In order to accept incoming connections you must call the ServerSocket.accept() method. The accept()method returns a Socket which behaves like an ordinary Java Socket. Here is how that looks:

ServerSocket serverSocket = new ServerSocket(9000);

boolean isStopped = false;
while(!isStopped){
    Socket clientSocket = serverSocket.accept();

    //do something with clientSocket
}

Only one incoming connection is opened for each call to the accept() method.

  • Closing Client Sockets

Once a client request is finished, and no further requests will be received from that client, you must close that Socket, just like you would close a normal client Socket. This is done by calling:

socket.close();

  • Closing Server Sockets

Once the server is to shut down you need to close the ServerSocket. This is done by calling:

serverSocket.close();

ServerSocket Class Methods

The java.net.ServerSocket class is used by server applications to obtain a port and listen for client requests.

The ServerSocket class has four constructors −

91.png


Client –Server Communication

  • When a client and server communicates to perform some operation they exchange information. For instance, the client will ask for a service to be performed, and the server will attempt to perform it, and send back a response telling the client of the result.

91.png

  • Let’s see a simple of  Client –Server Communication in which client sends a text and server receives it.

File: MyServer.java

 

import java.io.*;  

import java.net.*;  

public class MyServer {  

public static void main(String[] args){  

try{  

ServerSocket ss=new ServerSocket(6666);  

Socket s=ss.accept();//establishes connection   

DataInputStream dis=new DataInputStream(s.getInputStream());  

String  str=(String)dis.readUTF();  

System.out.println(“message= “+str);  

ss.close();  

}catch(Exception e){System.out.println(e);}  

}  

}  

File: MyClient.java

 

import java.io.*;  

import java.net.*;  

public class MyClient {  

public static void main(String[] args) {  

try{      

Socket s=new Socket(“localhost”,6666);  

DataOutputStream dout=new DataOutputStream(s.getOutputStream());  

dout.writeUTF(“Hello Server”);  

dout.flush();  

dout.close();  

s.close();  

}catch(Exception e){System.out.println(e);}  

}  

}  

  • In this example, client will write first to the server then server will receive and print the text. Then server will write to the client and client will receive and print the text. The step goes on.

File: MyServer.java

 

import java.net.*;  

import java.io.*;  

class MyServer{  

public static void main(String args[])throws Exception{  

ServerSocket ss=new ServerSocket(3333);  

Socket s=ss.accept();  

DataInputStream din=new DataInputStream(s.getInputStream());  

DataOutputStream dout=new DataOutputStream(s.getOutputStream());  

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

  String str=“”,str2=“”;  

while(!str.equals(“stop”)){  

str=din.readUTF();  

System.out.println(“client says: “+str);  

str2=br.readLine();  

dout.writeUTF(str2);  

dout.flush();  

}  

din.close();  

s.close();  

ss.close();  

}}  

 

File: MyClient.java

 

import java.net.*;  

import java.io.*;  

class MyClient{  

public static void main(String args[])throws Exception{  

Socket s=new Socket(“localhost”,3333);  

DataInputStream din=new DataInputStream(s.getInputStream());  

DataOutputStream dout=new DataOutputStream(s.getOutputStream());  

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

  

String str=“”,str2=“”;  

while(!str.equals(“stop”)){  

str=br.readLine();  

dout.writeUTF(str);  

dout.flush();  

str2=din.readUTF();  

System.out.println(“Server says: “+str2);  

}  

  

dout.close();  

s.close();  

}}  

 

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s