Program for Client - Server Communication using Java

Program for Client - Server Communication using Java


Client Program

       Socket object must be created to communicate with server. The Socket object is clsct in the following program . 

import java.io.*;
import java.net.*;
import java.util.*;
class Client

{
            public static void main(String args[])
            {
            try
            {
                        BufferedReader in=new BufferedReader(new InputStreamReader(System.in));
                        Socket clsct=new Socket("127.0.0.1",139);
                        DataInputStream din=new DataInputStream(clsct.getInputStream());
                        DataOutputStream dout=new DataOutputStream(clsct.getOutputStream());
                        System.out.println("Enter String");
                        String str=in.readLine();
                        dout.writeBytes(str+'\n');
                        String str1=din.readLine();
                        System.out.println("The String is: "+str1);
                        clsct.close();
            }
            catch (Exception e)
            {
            System.out.println(e);
            }
            }
}

Server
     The ServerSocket object is created to create specific port in server side for client which is requesting to access the server. More than one ports are created for more number of clients. Each port have only one client.

     The ServerSocket object is obj in the following program. 

import java.io.*;
import java.net.*;
import java.util.*;
class Server
{
            public static void main(String args[])
            {
            try
            {
                        ServerSocket obj=new ServerSocket(139);
                        while(true)
                        {
                                    Socket obj1=obj.accept();
                                    DataInputStream din=new DataInputStream(obj1.getInputStream());
                                    DataOutputStream dout=new DataOutputStream(obj1.getOutputStream());
                                    String str=din.readLine();
                                    dout.writeBytes(str+'\n');
                                    System.out.println(str);
                        }
            }
            catch(Exception e)
            {
                        System.out.println(e);
            }
            }
}

Output

E:\mayil\networks>java Client
Enter String
mayil
The String is: mayil

E:\mayil\networks>java Server
mayil

No comments:

Post a Comment

Creating Objects

Creating Objects                  Creating objects means to allocate memory space for all the instance variables of the objects. S...