Showing posts with label Client Server Program. Show all posts


Sender Side Program

import java.io.*;
import java.net.*;
class slidingSender
{
    public void process()
    {
        try
        {
            ServerSocket server= new ServerSocket(2500);
            Socket client = server.accept();
            BufferedReader user=new BufferedReader(new InputStreamReader(System.in));
            BufferedReader br=new BufferedReader(new InputStreamReader(client.getInputStream()));
            PrintWriter pr=new PrintWriter(client.getOutputStream(),true);
            String buf[]=new String[8];
            int index=0,sws=8,rws;
            String ch;
            do
            {
                System.out.println("Enter the number of frame send to the receiver:");
                int nf=Integer.parseInt(user.readLine());
                pr.println(nf);
                if(nf<=sws-1)
                {
                    System.out.println("Enter the "+nf+" Message send to the receiver");
                    for(int i=0;i<nf;i++)
                    {
                        buf[i]=user.readLine();
                        pr.println(buf[i]);

                    }
                   
                    sws=sws-nf;
                    int ackno=Integer.parseInt(br.readLine());
                    System.out.println("Acknowledge Received For the Frame"+ackno);
                    sws=sws+nf;

                }
                else
                {
                    System.out.println("SENDER WINDOW SIZE EXCEEDS");
                }
                System.out.println("Do You Want To Continue(y/n)");
                ch=user.readLine();
                pr.println(ch);
            }
            while(ch.equals("y"));
        }
        catch(Exception e){}
    }
    public static void main(String arg[])
    {
        slidingSender s= new slidingSender();
        s.process();
    }

}

Receiver Side Program

import java.io.*;
import java.net.*;

class slidingReceiver
{
    public void process()
    {
        try
        {
            Socket client = new Socket(InetAddress.getLocalHost(),2500);
            BufferedReader br = new BufferedReader(new InputStreamReader(client.getInputStream()));
            BufferedReader user=new BufferedReader(new InputStreamReader(System.in));
            PrintWriter pr=new PrintWriter(client.getOutputStream(),true);
            int index=0,rws=8;
            String buf[]=new String[8];
            String ch;
            while(true)
            {
                do
                {
                    int nf=Integer.parseInt(br.readLine());
                    if(nf<rws-1)
                    {
                        for(int i=0;i<nf;i++)
                        {
                            buf[index]=br.readLine();
                            System.out.println(index);
                            System.out.println(buf[index]);
                            index=(index +1)%rws;
                            System.out.println(index);
                        }
                        rws = rws - nf;                      
                        System.out.println("Acknowledge Sent To Sender");
                        pr.println(index);
                        rws=rws+nf;
                    }
                    else
                    {
                        break;
                    }
                    ch=br.readLine();
                }
                while(ch.equals("y"));
            }
        }
        catch(Exception e){}
    }
    public static void main(String arg[])
    {
        slidingReceiver r= new slidingReceiver();
        r.process();
    }
}

How to run:

  1. First run Sender program 
  2. Then next run Receiver program
  3. Give input from Sender side

Sender Side Output:

Enter the number of frame send to the receiver:
3
Enter the 3 Message send to the receiver
hi
good
evening
Acknowledge Received For the Frame3
Do You Want To Continue(y/n)
n

Receiver Side Output:

0 
hi 
1 
1 
good 
2 
2 
evening 
3 
Acknowledge Sent To Sender 


Multicast Sender

import java.net.*;
import java.io.*;

class MulticastSender implements Runnable
{
    static int port;
    static MulticastSocket ms;
    static String group;
    static int status = 0 ;
    MulticastSender() throws Exception
    {
        port = 5000;
        group = "225.4.5.6";
        ms = new MulticastSocket(4000);
    }
    public void run()
    {
        while(true)
        {
            try
            {
                BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
                byte sbuf[] = new byte[2000];
                sbuf = br.readLine().getBytes();
                DatagramPacket spack = new DatagramPacket(sbuf, sbuf.length,
                                                 InetAddress.getByName(group), port);
                ms.send(spack);                                                
               
            }catch(Exception e){ System.out.println(e);}
        }
    }
    public static void main(String args[]) throws Exception
    {
        MulticastSender sender = new MulticastSender();
        Thread t = new Thread(sender);
               
        ms.joinGroup(InetAddress.getByName(group));
        t.start();
       
        int count =0;
        byte rbuf[] = new byte[1000];
        while(true)
        {
            DatagramPacket rpack =new DatagramPacket(rbuf,rbuf.length);
            ms.receive(rpack);
            String str = new String(rpack.getData(),0,rpack.getLength());
            if(str.equalsIgnoreCase("join"))
            {
                count++;
                System.out.println("Client joined the group");
                System.out.println("\ncurrently " + count + " client/clients is/are in the group");
               
            }
            else if(str.equalsIgnoreCase("leave"))
            {
                count--;
                System.out.println("Client left the group");
                System.out.println("\ncurrently " + count + " client/clients is/are in the group");
                if(count == 0)
                {
                    ms.leaveGroup(InetAddress.getByName(group));
                    ms.close();
                    break;
                }
            }
        }
    }
}

Multicast Receiver

import java.io.*;
import java.net.*;
class MulticastReceiver implements Runnable
{
    static MulticastSocket ms;
    static int port;
    static int status = 0;
    MulticastReceiver() throws Exception
    {
        port = 5000;
        ms= new MulticastSocket(port);
    }
    public void run()
    {
        while(true)
        {
            try
            {
                byte rbuf[] = new byte[2000];
                DatagramPacket  rpack = new DatagramPacket(rbuf,rbuf.length);
                if (status == 1)
                {
                    ms.close();
                    break;
                }
                ms.receive(rpack);
                System.out.println(new String(rpack.getData(),0,rpack.getLength()));
            }catch(Exception e){System.out.println(e);}
        }
    }
   
    public static void main(String args[]) throws Exception
    {
        MulticastReceiver mr =new MulticastReceiver();
        Thread t = new Thread(mr);
       
        String group = "225.4.5.6";
      
        System.out.println("Do you wish to join the group?");
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        if(br.readLine().equalsIgnoreCase("yes"))
        {
            ms.joinGroup(InetAddress.getByName(group));
           
            byte sbuf[] = new byte[2000];
            sbuf = "join".getBytes();
            DatagramPacket spack = new DatagramPacket(sbuf, sbuf.length,InetAddress.getByName("localhost"),4000);
            ms.send(spack);
          
            System.out.println("Joined the group");
            t.start();
            while(true)
            {
                if(br.readLine().equalsIgnoreCase("leave"))
                {
                    status = 1;
                    byte sbuf2[] = new byte[2000];
                    sbuf2 = "leave".getBytes();
                    DatagramPacket spack2 = new DatagramPacket(sbuf2,sbuf2.length,InetAddress.getByName("localhost"),4000);
                    ms.send(spack2);
                    ms.leaveGroup(InetAddress.getByName(group));
                    break;
                }
            }
        }
    }
}

How to run:

  1. First run Receiver program 
  2. Then next run Sender program in single or multiple times
  3. Give input "yes" from Receiver side
  4. Next give input in Sender side

Receiver Side Output:

Do you wish to join the group?
yes
Joined the group
hi

Sender Side Output:

Client joined the group

currently 1 client/clients is/are in the group
hi

Client Side Program

import java.io.*;
import java.net.*;
class TCPClient {

  public static void main(String args[]) throws Exception
  {
       String sentence;
       String modifiedSentence;
        BufferedReader inFromUser =
         new BufferedReader(new InputStreamReader(System.in));

      Socket clientSocket = new Socket("127.0.0.1", 6324);

        DataOutputStream outToServer =
          new DataOutputStream(clientSocket.getOutputStream());
   
       BufferedReader inFromServer =
          new BufferedReader(new
            InputStreamReader(clientSocket.getInputStream()));

        sentence = inFromUser.readLine();
        outToServer.writeBytes(sentence + '\n');

        modifiedSentence = inFromServer.readLine();

        System.out.println("FROM SERVER: " + modifiedSentence);

        clientSocket.close();
                 
    }
}

Server Side Program

import java.io.*;
import java.net.*;

class TCPServer {

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

      ServerSocket welcomeSocket = new ServerSocket(6324);
 
      while(true) {
 
            Socket connectionSocket = welcomeSocket.accept();

           BufferedReader inFromClient =
              new BufferedReader(new
              InputStreamReader(connectionSocket.getInputStream()));

          
DataOutputStream  outToClient =
             new DataOutputStream(connectionSocket.getOutputStream());

           clientSentence = inFromClient.readLine();
           System.out.println("FROM client:" + clientSentence); 
           capitalizedSentence = clientSentence.toUpperCase() + '\n';
           outToClient.writeBytes(capitalizedSentence);
        }
    }
}

How to run:

  1. First run server program then next run client program
  2. Give input from client side
  3. Next give input in server side

Client Side Output:

hi
FROM SERVER: HI

Server Side Output:

FROM client:hi
hi da

Client Side Program

import java.io.*; 
import java.net.*; 
class ChatClient extends Thread 
{ 
    Socket s; 
    static PrintWriter out; 
    static BufferedReader read,in; 
    Thread t;

    ChatClient() throws Exception 
    { 
        s = new Socket("127.0.0.1",5000); 
        System.out.println("client connected to server");  
        read = new BufferedReader(new InputStreamReader(System.in)); 
        in=new BufferedReader(new InputStreamReader(s.getInputStream())); 
        out=new PrintWriter(s.getOutputStream()); 
        t=new Thread(this); 
        t.start(); 
    } 
     
    public void run() 
    { 
        String str1; 
        while(true) 
        { 
            try 
            { 
                      str1=in.readLine(); 
                      System.out.println("\n"+"From server: "+str1); 
                } 
                catch(Exception e) 
                { 
                       System.out.println(e); 
            } 
        } 
    }

    public static void main(String args[]) throws Exception 
    { 
        String str2; 
        new ChatClient(); 
        while(true) 
        { 
            str2=read.readLine(); 
            out.println(str2); 
            out.flush();   
           } 
    } 
}

Server Side Program

import java.io.*;
import java.net.*;

class ChatServerTCP extends Thread
{
    ServerSocket server;
    Socket s;
    static PrintWriter out;
    static BufferedReader read,in;
    Thread t;

ChatServerTCP() throws Exception
{
    server = new ServerSocket(5000);
    System.out.println("Server is waiting for client");
    s=server.accept();
    System.out.println("connection is established "+s.getInetAddress());
    read = new BufferedReader(new InputStreamReader(System.in));
    in=new BufferedReader(new InputStreamReader(s.getInputStream()));
    out=new PrintWriter(s.getOutputStream());
    t=new Thread(this);
    t.start();
}

public void run()
{
    String str1;
    while(true)
    {
        try
            {
                  str1=in.readLine();
                  System.out.println("\n"+"From client: "+str1);
            }
            catch(Exception e)
            {
                   System.out.println(e);
            }
      }
}

public static void main(String args[]) throws Exception
{
    ChatServerTCP cs = new ChatServerTCP();
    String str2;
    while(true)
    {
             str2=read.readLine();
             out.println(str2);
             out.flush(); 
       }
}
}

How to run:

  1. First run server program then next run client program
  2. Give input from client side
  3. Next give input in server side

Client Side Output:

client connected to server
hi

From server: hi da

how r u?

From server: fine

Server Side Output:

Server is waiting for client 
connection is established /127.0.0.1 

From client: hi 
hi da
From client:

From client: how r u? 
fine

Client / Server Chatting Program

Friday, 19 June 2015
Posted by Unknown
 

Client / Server Chatting Program 

Client / Server Connection Program

100% works...!

Client Side Program:

import java.io.*;
import java.net.*;
import java.util.Scanner;
class CLChatClient {
    static final String DEFAULT_PORT = "1728";   
    static final String HANDSHAKE = "CLChat";   
    static final char MESSAGE = '0';
    static final char CLOSE = '1';
    public static void main(String[] args) {
        String computer; 
        String portStr;  
        int port;  
        Socket connection;     
        BufferedReader incoming;  // Stream for receiving data from server.
        PrintWriter outgoing;     // Stream for sending data to server.
        String messageOut;        // A message to be sent to the server.
        String messageIn;         // A message received from the server.
        Scanner userInput;        // A wrapper for System.in, for reading                   
        if (args.length == 0) {
            Scanner stdin = new Scanner(System.in);
            System.out.print("Enter computer name or IP address: ");
            computer = stdin.nextLine();
            System.out.print("Enter port, or press return to use default:");
            portStr = stdin.nextLine();
            if (portStr.length() == 0)
                portStr = DEFAULT_PORT;
        }
        else {
            computer = args[0];
            if (args.length == 1)
                portStr = DEFAULT_PORT;
            else
                portStr = args[1];
        }
        try {
            port= Integer.parseInt(portStr);
            if (port <= 0 || port > 65535)
                throw new NumberFormatException();
        }
        catch (NumberFormatException e) {
            System.out.println("Illegal port number, " + args[1]);
            return;
        }
        try {
            System.out.println("Connecting to " + computer + " on port " + port);
            connection = new Socket(computer,port);
            incoming = new BufferedReader(
                    new InputStreamReader(connection.getInputStream()) );
            outgoing = new PrintWriter(connection.getOutputStream());
            outgoing.println(HANDSHAKE);  // Send handshake to client.
            outgoing.flush();
            messageIn = incoming.readLine();  // Receive handshake from client.
            if (! messageIn.equals(HANDSHAKE) ) {
                throw new IOException("Connected program is not CLChat!");
            }
            System.out.println("Connected.  Enter your first message.");
        }
        catch (Exception e) {
            System.out.println("An error occurred while opening connection.");
            System.out.println(e.toString());
            return;
        }

        /* Exchange messages with the other end of the connection until one side or
           the other closes the connection.  This client program sends the first message.
           After that,  messages alternate strictly back and forth. */

        try {
            userInput = new Scanner(System.in);
            System.out.println("NOTE: Enter 'quit' to end the program.\n");
            while (true) {
                System.out.print("SEND:      ");
                messageOut = userInput.nextLine();
                if (messageOut.equalsIgnoreCase("quit"))  {
                        // User wants to quit.  Inform the other side
                        // of the connection, then close the connection.
                    outgoing.println(CLOSE);
                    outgoing.flush();
                    connection.close();
                    System.out.println("Connection closed.");
                    break;
                }
                outgoing.println(MESSAGE + messageOut);
                outgoing.flush();
                if (outgoing.checkError()) {
                    throw new IOException("Error occurred while transmitting message.");
                }
                System.out.println("WAITING...");
                messageIn = incoming.readLine();
                if (messageIn.length() > 0) {
                        // The first character of the message is a command. If
                        // the command is CLOSE, then the connection is closed. 
                        // Otherwise, remove the command character from the
                        // message and proceed.
                    if (messageIn.charAt(0) == CLOSE) {
                        System.out.println("Connection closed at other end.");
                        connection.close();
                        break;
                    }
                    messageIn = messageIn.substring(1);
                }
                System.out.println("RECEIVED:  " + messageIn);
            }
        }
        catch (Exception e) {
            System.out.println("Sorry, an error has occurred.  Connection lost.");
            System.out.println(e.toString());
            System.exit(1);
        }
    }  // end main()
} //end class CLChatClient

Server Side Program:

import java.io.*;
import java.net.*;
import java.util.Scanner;
public class CLChatServer {
    static final int DEFAULT_PORT = 1728;
    static final String HANDSHAKE = "CLChat";
    static final char MESSAGE = '0';
    static final char CLOSE = '1';
    public static void main(String[] args) {
        int port;   // The port on which the server listens.
        ServerSocket listener;  // Listens for a connection request.
        Socket connection;      // For communication with the client.
        BufferedReader incoming;  // Stream for receiving data from client.
        PrintWriter outgoing;     // Stream for sending data to client.
        String messageOut;        // A message to be sent to the client.
        String messageIn;         // A message received from the client.
        Scanner userInput;        // A wrapper for System.in, for reading           
        if (args.length == 0)
            port = DEFAULT_PORT;
        else {
            try {
                port= Integer.parseInt(args[0]);
                if (port < 0 || port > 65535)
                    throw new NumberFormatException();
            }
            catch (NumberFormatException e) {
                System.out.println("Illegal port number, " + args[0]);
                return;
            }
        }
        try {
            listener = new ServerSocket(port);
            System.out.println("Listening on port " + listener.getLocalPort());
            connection = listener.accept();
            listener.close();
            incoming = new BufferedReader(
                    new InputStreamReader(connection.getInputStream()) );
            outgoing = new PrintWriter(connection.getOutputStream());
            outgoing.println(HANDSHAKE);  // Send handshake to client.
            outgoing.flush();
            messageIn = incoming.readLine();  // Receive handshake from client.
            if (! HANDSHAKE.equals(messageIn) ) {
                throw new Exception("Connected program is not a CLChat!");
            }
            System.out.println("Connected.  Waiting for the first message.");
        }
        catch (Exception e) {
            System.out.println("An error occurred while opening connection.");
            System.out.println(e.toString());
            return;
        }

        /* Exchange messages with the other end of the connection until one side
           or the other closes the connection.  This server program waits for
           the first message from the client.  After that, messages alternate
           strictly back and forth. */
        try {
            userInput = new Scanner(System.in);
            System.out.println("NOTE: Enter 'quit' to end the program.\n");
            while (true) {
                System.out.println("WAITING...");
                messageIn = incoming.readLine();
                if (messageIn.length() > 0) {
                        // The first character of the message is a command. If
                        // the command is CLOSE, then the connection is closed.
                        // Otherwise, remove the command character from the
                        // message and proceed.
                    if (messageIn.charAt(0) == CLOSE) {
                        System.out.println("Connection closed at other end.");
                        connection.close();
                        break;
                    }
                    messageIn = messageIn.substring(1);
                }
                System.out.println("RECEIVED:  " + messageIn);
                System.out.print("SEND:      ");
                messageOut = userInput.nextLine();
                if (messageOut.equalsIgnoreCase("quit"))  {
                        // User wants to quit.  Inform the other side
                        // of the connection, then close the connection.
                    outgoing.println(CLOSE);
                    outgoing.flush();  // Make sure the data is sent!
                    connection.close();
                    System.out.println("Connection closed.");
                    break;
                }
                outgoing.println(MESSAGE + messageOut);
                outgoing.flush(); // Make sure the data is sent!
                if (outgoing.checkError()) {
                    throw new IOException("Error occurred while transmitting message.");
                }
            }
        }
        catch (Exception e) {
            System.out.println("Sorry, an error has occurred.  Connection lost.");
            System.out.println("Error:  " + e);
            System.exit(1);
        }
    }  // end main()
} //end class CLChatServer

Client Side Output:

Enter computer name or IP address: VIJAY-PC 
Enter port, or press return to use default:1728 
Connecting to VIJAY-PC on port 1728 
Connected.  Enter your first message. 
NOTE: Enter 'quit' to end the program. 

SEND:      hi i am vijay... 
WAITING... 
RECEIVED:  hi i am kumar 
SEND:      wt dng? 
WAITING... 
RECEIVED:  simply chating with u 
SEND:      k bye 
WAITING... 
RECEIVED:  bye 
SEND:      quit 
Connection closed.

Server Side Output:

Listening on port 1728
Connected.  Waiting for the first message.
NOTE: Enter 'quit' to end the program.

WAITING...
RECEIVED:  hi i am vijay...
SEND:      hi i am kumar
WAITING...
RECEIVED:  wt dng?
SEND:      simply chating with u
WAITING...
RECEIVED:  k bye
SEND:      bye
WAITING...
Connection closed at other end.
Welcome to My Blog

Translate

Popular Post

Total Pageviews

- Copyright © Learning Java Program - Powered by Blogger -