top
upGrad KnowledgeHut SkillFest Sale!

Search

Java Tutorial

This module talks about a very simple one-way client and server setup, where a client connects and sends emails to the server, and the server uses socket link to view them. There are a lot of low-level things that need to happen for these things to work, but the Java API networking kit (java.net) takes care of all that, makingnetworkprogramming programmers very easy for developers. Client programming (Socket): We need a socket connection to connect to another device. A socket connection implies that both devices have data about the network place of each other (IP Address) and TCP port. The java.net.Socket class is a socket. Opening a socket: Socket socket = new Socket(“127.0.0.1”, 6000) 1st argument is a server's IP address.  2nd argument is a port of TCP.  Streams are used to input and output the information to communicate over a socket connection. The link to the socket will be explicitly closed once the message is sent to the server. Client keeps reading the user inputs in the program and sends it to the server until it types "Finished" Java Implementation import java.net.*;   import java.io.*;   public class Client   {   // initialize socket and input output streams   private Socket socket = null;   private DataInputStream input = null;   private DataOutputStream out = null;   // constructor to put ip address and port   public Client(String address, int port)   {   try  {   socket = new Socket(address, port);   System.out.println("Connected");   input = new DataInputStream(System.in);   out = new DataOutputStream(socket.getOutputStream());   }   catch(UnknownHostException u)   {   System.out.println(u);   }   catch(IOException i)   {   System.out.println(i);   }   String line = "";   while (!line.equals("Finished"))   {   try  {   line = input.readLine();   out.writeUTF(line);   }   catch(IOException i)   {   System.out.println(i);   }   }   try  {   input.close();   out.close();   socket.close();   }   catch(IOException i)   {   System.out.println(i);   }   }   public static void main(String args[])   {   Client client = new Client("127.0.0.1", 6000);   }   }Server Programming: 2 sockets are required to write a server application. A ServerSocket waiting for demands from the client (when a client creates a fresh/new Socket)) A simple old socket that can be used for client communication. The technique/method getOutputStream() is used to deliver outputs via the socket. It is essential to close the link after completion by closing both the socket and the input / output streams. import java.net.*;   import java.io.*;   public class Server   {   //initialize socket and input stream   private Socket socket = null;   private ServerSocket server = null;   private DataInputStream in = null;   public Server(int port)   {   try  {   server = new ServerSocket(port);   System.out.println("Server started");   System.out.println("Waiting for a client ...");   socket = server.accept();   System.out.println("Client accepted");   in = new DataInputStream(   new BufferedInputStream(socket.getInputStream()));   String line = "";   while (!line.equals("Finished"))   {   try  {   line = in.readUTF();   System.out.println(line);   }   catch(IOException i)   {   System.out.println(i);   }   }   System.out.println("Closing connection");   // close connection   socket.close();   in.close();   }   catch(IOException i)   {   System.out.println(i);   }   }   public static void main(String args[])   {   Server server = new Server(6000);   }   }  Points to remember: Server application on a particular port that is 6000 allows a ServerSocket. This begins listening to our server for client demands for port 6000. Then Server creates a fresh socket for the client to interact. socket = server.accept() The accept() technique/method blocks until the server is linked by the client Instead we take input from the socket using getInputStream() technique/Method. Our server will receive emails until the user sends "Finished" Programmer then close the link/connection after he has finished by closing the socket and the input stream. Compile both client and server programs to run/execute the client and server application on your computer. First execute the application on the server and then execute the application on the client. To run on Terminal or Command Prompt Open 2 windows, one for Server and another for Client -  First execute the Server java application as , $ java Server Server startedWaiting for a client … - Then execute the Client java application on another terminal as, $ java Client It will show – Connected and the server accepts the client and shows, Client accepted - Then in the client window you can begin typing messages. Here's a sample client input Hello How are you ? Finished Which the Server simultaneously receives and shows, Hello How are you ? Finished Closing connection Note that "Finished" sending closes the link between the client and the server just as said before. Using IDE:  Compile both on two separate terminals or tabs.  Execute the Server java program first  After that execute the Client java program  Type posts in the client window that the server window will receive and display at the same time.  Type Finished to terminate. 
logo

Java Tutorial

Networking

This module talks about a very simple one-way client and server setup, where a client connects and sends emails to the server, and the server uses socket link to view them. There are a lot of low-level things that need to happen for these things to work, but the Java API networking kit (java.net) takes care of all that, makingnetworkprogramming programmers very easy for developers. 

Client programming (Socket): 

We need a socket connection to connect to another device. A socket connection implies that both devices have data about the network place of each other (IP Address) and TCP port. The java.net.Socket class is a socket. Opening a socket: 

Socket socket = new Socket(“127.0.0.1”, 6000) 

  • 1st argument is a server's IP address.  
  • 2nd argument is a port of TCP.  

Streams are used to input and output the information to communicate over a socket connection. 

The link to the socket will be explicitly closed once the message is sent to the server. Client keeps reading the user inputs in the program and sends it to the server until it types "Finished" 

Java Implementation 

import java.net.*;  
import java.io.*;  
public class Client  
{  
    // initialize socket and input output streams  
    private Socket socket   = null;  
    private DataInputStream  input   = null;  
    private DataOutputStream out     = null;  
    // constructor to put ip address and port  
    public Client(String address, int port)  
    {  
        try 
        {  
            socket = new Socket(address, port);  
            System.out.println("Connected");  
            input  = new DataInputStream(System.in);  
            out    = new DataOutputStream(socket.getOutputStream());  
        }  
        catch(UnknownHostException u)  
        {  
            System.out.println(u);  
        }  
        catch(IOException i)  
        {  
            System.out.println(i);  
        }  
        String line = "";  
        while (!line.equals("Finished"))  
        {  
            try 
            {  
                line = input.readLine();  
                out.writeUTF(line);  
            }  
            catch(IOException i)  
            {  
                System.out.println(i);  
            }  
        }  
        try 
        {  
            input.close();  
            out.close();  
            socket.close();  
        }  
        catch(IOException i)  
        {  
            System.out.println(i);  
        }  
    }  
    public static void main(String args[])  
    {  
        Client client = new Client("127.0.0.1", 6000);  
    }  
}

Server Programming: 

2 sockets are required to write a server application. 

  • A ServerSocket waiting for demands from the client (when a client creates a fresh/new Socket)) 
  • A simple old socket that can be used for client communication. 

The technique/method getOutputStream() is used to deliver outputs via the socket. 

It is essential to close the link after completion by closing both the socket and the input / output streams. 

import java.net.*;  
import java.io.*;  
public class Server  
{  
    //initialize socket and input stream  
    private Socket          socket   = null;  
    private ServerSocket    server   = null;  
    private DataInputStream in       =  null;  
    public Server(int port)  
    {  
        try 
        {  
            server = new ServerSocket(port);  
            System.out.println("Server started");  
            System.out.println("Waiting for a client ...");  
            socket = server.accept();  
            System.out.println("Client accepted");  
            in = new DataInputStream(  
                new BufferedInputStream(socket.getInputStream()));  
            String line = "";  
            while (!line.equals("Finished"))  
            {  
                try 
                {  
                    line = in.readUTF();  
                    System.out.println(line);  
                }  
                catch(IOException i)  
                {  
                    System.out.println(i);  
                }  
            }  
            System.out.println("Closing connection");  
            // close connection  
            socket.close();  
            in.close();  
        }  
        catch(IOException i)  
        {  
            System.out.println(i);  
        }  
    }  
    public static void main(String args[])  
    {  
        Server server = new Server(6000);  
    }  
}  

Points to remember: 

  • Server application on a particular port that is 6000 allows a ServerSocket. This begins listening to our server for client demands for port 6000. 
  • Then Server creates a fresh socket for the client to interact. 

socket = server.accept() 

  • The accept() technique/method blocks until the server is linked by the client 
  • Instead we take input from the socket using getInputStream() technique/Method. Our server will receive emails until the user sends "Finished" 
  • Programmer then close the link/connection after he has finished by closing the socket and the input stream. 

Compile both client and server programs to run/execute the client and server application on your computer. First execute the application on the server and then execute the application on the client. 

To run on Terminal or Command Prompt 

Open 2 windows, one for Server and another for Client 

-  First execute the Server java application as , 

$ java Server 

Server started
Waiting for a client … 

- Then execute the Client java application on another terminal as, 

$ java Client 

It will show – Connected and the server accepts the client and shows, 

Client accepted 

- Then in the client window you can begin typing messages. Here's a sample client input 

Hello 

How are you ? 

Finished 

Which the Server simultaneously receives and shows, 

Hello 

How are you ? 

Finished 

Closing connection 

Note that "Finished" sending closes the link between the client and the server just as said before. 

Using IDE: 

  •  Compile both on two separate terminals or tabs. 
  •  Execute the Server java program first 
  •  After that execute the Client java program 
  •  Type posts in the client window that the server window will receive and display at the same time. 
  •  Type Finished to terminate. 

Leave a Reply

Your email address will not be published. Required fields are marked *

Comments

protective orders in virginia

Keep sharing blogs like this one; they are quite good. You have given everyone in this blog access to a wealth of information.

Johnfrance

Thank you for your valuable information.

sam

Thank you for this wonderful article!

Belay Abera

This article was really helpful to me, thank you!

dfsdf

super article!