Posted by : Unknown Friday 19 June 2015

 

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.

Leave a Reply

Subscribe to Posts | Subscribe to Comments

Welcome to My Blog

Translate

Popular Post

Total Pageviews

Blog Archive

- Copyright © Learning Java Program - Powered by Blogger -