LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Programming (https://www.linuxquestions.org/questions/programming-9/)
-   -   IN JAVA, how to do a multi chat client in java with the option of private message ? (https://www.linuxquestions.org/questions/programming-9/in-java-how-to-do-a-multi-chat-client-in-java-with-the-option-of-private-message-753166/)

nicolasd 09-06-2009 06:41 PM

IN JAVA, how to do a multi chat client in java with the option of private message ?
 
hi all

i would like to know how to do a chat client server program IN JAVA where multiple clients can connect to the server
and how to be able to see a client send a private message to one of the specify client ?

" the message from the client will go to the server and after will go to the specify client "


at the moment i can do some private message but the message is coming from the server which is gay
its working but not the good way
so plz help me out with this

im new to client / server application :p

ty for the help !

Code:


//server

import java.io.*;
import java.net.*;
import java.util.Scanner;
import java.util.Random;

public class MultiThreadChatServer{

    // Declaration section:
    // declare a server socket and a client socket for the server
    // declare an input and an output stream
   
    static  Socket clientSocket = null;
    static  ServerSocket serverSocket = null;

    // This chat server can accept up to 10 clients' connections

    static  clientThread t[] = new clientThread[10];         
 
   
    public static void main(String args[]) {
       
        // The default port


       
        // Initialization section:
        // Try to open a server socket on port port_number (default 2222)
        // Note that we can't choose a port less than 1023 if we are not
        // privileged users (root)

        try {
            serverSocket = new ServerSocket(5555);
        }
        catch (IOException e)
            {System.out.println(e);}
       
        // Create a socket object from the ServerSocket to listen and accept
        // connections.
        // Open input and output streams for this socket will be created in
        // client's thread since every client is served by the server in
        // an individual thread
       
        while(true){
            try {
                clientSocket = serverSocket.accept();
                for(int id =0; id<=9; id++){
                    if(t[id]==null)
                        {
                            (t[id] = new clientThread(clientSocket,t,id)).start();
                            break;
                        }
                }
            }
            catch (IOException e) {
                System.out.println(e);}
        }
    }
}

// This client thread opens the input and the output streams for a particular client,
// ask the client's name, informs all the clients currently connected to the
// server about the fact that a new client has joined the chat room,
// and as long as it receive data, echos that data back to all other clients.
// When the client leaves the chat room this thread informs also all the
// clients about that and terminates.

class clientThread extends Thread
{
   
    DataInputStream is = null;
    PrintStream os = null;
    Socket clientSocket = null;     
    clientThread t[];
    clientThread ct;
    int idClient;
   
    public clientThread(Socket clientSocket, clientThread[] t,int id)
    {
            this.clientSocket=clientSocket;
        this.t=t;
        idClient = id;
    }
   
            public void run()
            {
                    String line;
                    String name;
       
                    try
                    {
                            is = new DataInputStream(clientSocket.getInputStream());
                            os = new PrintStream(clientSocket.getOutputStream());
                            idClient++;
       
                            os.println("Enter your name.");
                            name = is.readLine();
                            os.println("Hello "+name+"your user id is : " + idClient);
                    System.out.println("Hello "+name+"your user id is : " + idClient);
                            for (int idClient = 0; idClient<=9; idClient++)
                              if (t[idClient]!=null && t[idClient]!=this) 
                                    t[idClient].os.println("*** A new user "+name+" entered the chat room !!! ***" );
           
         
                            while (true)
                            {
                                    line = is.readLine();
                                   
                                    if (line.startsWith("/quit")) break;
           
 
                                    if(line.startsWith("/getid"))
                                    {     
                                            os.println("<"+name+" > Your id is :" + idClient);                     
                                    }             
                                   
                                    if(line.startsWith("/menu"))
                                    {
                                            for (int idClient=0; idClient<=9; idClient++)
                                              if (t[idClient]!=null && t[idClient]==this)
                                                    t[idClient].os.println("1.Show all Name of the clients\n2. Show your name\n3.Send a file to the server\n4.Receive a file to the server\n5.Quit");         
                                    }
                                    if(line.startsWith("/priv"))
                                    {
                                              Scanner sr = new Scanner(System.in);
                                                System.out.println("priv message to ?");
                                                int test = sr.nextInt();
                                                ct = t[test];
                                          String message = sr.next();
                                          ct.os.println("<"+name+"> "+ message);
                                    }
           
           
            /*
            *
                Scanner sr = new Scanner(System.in);
               
        System.out.println("Which number do you wanna see ? \n");
       
        int number = sr.nextInt();
        int aInt = Integer.parseInt(aString);
            System.out.println(ia[number]);
            * */
                                   
           
               
                                           
            /*for        (int idClient =0; idClient <=9; idClient ++)       
            {
              if (t[idClient]!=null) 
              {
                      System.out.println("Private Message for who ? ");
                      int number = is.readInt();
                      ct = t[number];
                   
              }
            }*/
                    /*System.out.println("Private Message for who ? ");
            String number = is.readLine();
            int aInt = Integer.parseInt(number);
            ct = t[aInt];
            ct.os.println("<"+name+"> "+line);*/
                                   
                                    for (int idClient=0; idClient<=9; idClient++)
                                            if (t[idClient]!=null && t[idClient]!=this)
                                                  t[idClient].os.println("<"+name+"> "+line);         
            }
         
            for (int idClient=0; idClient<=9; idClient++)
                  if (t[idClient]!=null && t[idClient]!=this) 
                    t[idClient].os.println("*** The user "+name+" is leaving the chat room !!! ***" );
           
            os.println("*** Bye "+name+" ***");

            // Clean up:
            // Set to null the current thread variable such that other client could
            // be accepted by the server

            for (int idClient=0; idClient<=9; idClient++)
              if (t[idClient]==this)
                    t[idClient]=null; 
               
            // close the output stream
            // close the input stream
            // close the socket
            try
            {                   
                    sleep(50);
            }
            catch(Exception e)
            {
            };
            is.close();
            os.close();
            clientSocket.close();
        }
        catch(IOException e)
        {
        };
     
    }   
}

//client
import java.io.*;
import java.net.*;

public class MultiThreadChatClient implements Runnable
{
 
    static Socket clientSocket = null;
    static PrintStream os = null;
    static DataInputStream is = null;
    static BufferedReader inputLine = null;
    static boolean closed = false;
   
    public static void main(String[] args)
    {
       
       
            try
            {
                    clientSocket = new Socket("192.168.0.100", 5555);
                    inputLine = new BufferedReader(new InputStreamReader(System.in));
                    os = new PrintStream(clientSocket.getOutputStream());
                    is = new DataInputStream(clientSocket.getInputStream());
            }
            catch(UnknownHostException e)
            {
                    System.err.println("Don't know about host "+5555);
            }
            catch(IOException e)
            {
                    System.err.println("Couldn't get I/O for the connection to the host "+5555);
            }
       
        // If everything has been initialized then we want to write some data
        // to the socket we have opened a connection to on port port_number
       
        if (clientSocket != null && os != null && is != null)
        {
            try
            {
               
                // Create a thread to read from the server
               
                new Thread(new MultiThreadChatClient()).start();
               
                while (!closed)
                {
                    os.println(inputLine.readLine());
        }
               
                // Clean up:
                // close the output stream
                // close the input stream
                // close the socket
               
                os.close();
                is.close();
                clientSocket.close(); 
            } catch (IOException e) {
                System.err.println("IOException:  " + e);
            }
        }
    }         
   
    public void run() {               
        String responseLine;
       
        // Keep on reading from the socket till we receive the "Bye" from the server,
        // once we received that then we want to break.
        try{
            while ((responseLine = is.readLine()) != null) {
                System.out.println(responseLine);
                if (responseLine.indexOf("*** Bye") != -1) break;
            }
            closed=true;
        } catch (IOException e) {
            System.err.println("IOException:  " + e);
        }
    }}


nadroj 09-06-2009 06:55 PM

Quote:

atm i can do some private message but the message is coming from the server which is gay
define "gay" (i.e. slow, insecure, not what you want/expect, etc). also, depending on the architecture (see below), the message can only come from the server (but since you didnt explain your situation, we dont know your expected behaviour or source of messages).

Quote:

its working but not the good way
define "its working" (i.e. what is working, and what you mean by "working", i.e. "the client can send a message to the chat server which can receive and display it). define "the good way".


you have given us a broad "question" and a pile of code and expect us to solve your problem. this isnt how these forums work, i dont think. please explain to us your problem, for example:

Quote:

would like to know how to do a chat client server program IN JAVA where multiple clients can connect to the server
is the architecture one where multiple chat clients connect to a central chat server, and each client sends and receives messages routed through the central server? or is it more of a peer-to-peer architecture where each client is somewhat of a "server" also (i.e. accepting incoming chat messages)? etc, etc

Quote:

and how to be able to send a private message to one of the specify client ?
this seems to be more of a "chat room" with the option of sending a message to an individual user in the room, rather than something like an MSN chat program, is this correct?

if you are doing a central chat server, then you must define a protocol (or should already do have this, and therefore need to modify your protocol) to accept some headers/meta data, such as "this message is only supposed to go to user 1234. if it is more of a peer-to-peer architecture, then your clients dont have to change, only the one sending the private message (in which case its just like sending a normal message to all X peers (X > 1), except you only send it to the expected IP/socket/user.

now, after you clear up or give us a better idea of what you are doing, please explain your problem. needless to say, im not going to go digging through your code to discover what the code is, what problem your having, and what way you want it to work.

nadroj 09-06-2009 07:07 PM

Quote:

" the message from the client will go to the server and after will go to the specify client "
i think this was an important detail you initially left out, but later added which is good. this tells us it is a "pure" client/server architecture. now:

Quote:

at the moment i can do some private message but the message is coming from the server which is gay
so right now all "global"/"normal" chat messages come from a client and are sent to the central server, which then sends it to all listening clients, correct? if you dont want the server to handle (receive then send) private messages, then the only other way is to have the two chat clients involved in the private message to interact directly. doing this, your application is not a pure client server and becomes somewhat of a hybrid client-server p2p (of course which is fine, but you have to tell us what you are looking for).

edit:
if this "hybrid" architecture is what you want, then you could use the following pseudocode (client "S" is private message sender, client "R" is private message recipient, server "C" is the central chat server), this is what would happen "behind the scenes", upon S typing a private message to R and clicking "send":

- S asks C to request a "private message connection" on port N for client R
- C tells R to start listening on S's socket (C already must know S's IP address, and has just received the port N, so it knows the socket to tell R)
- R receives this message, creates a separate thread dedicated to listening on the given socket, and replies to C that it is ready to receive the private message
- C receives response "OK" from R, and tells S it is ready to send directly to R
- S receives "OK" from C (which means R is ready), creates a new thread, and in this thread creates the socket on port N, sends the PM, closes the socket, kills this thread
- R (in its dedicated PM thread) receives the PM, closes its read side of the socket, kills this thread

R then has the message directly sent from S.

travishein 09-06-2009 07:11 PM

Break it down
 
Well, I think you would want to stay with the client-server model, right. I mean the only way to have a message go directly from one client to another client would be to somehow re-negotiate some kind of point-to-point connection after the clients initially connected to the server. But this would require a lot more complexity, and in most practical situations won't work due to firewalls; the client usually initiates the connection out to the server.

But either way, we would want to have more of a structured message format, such as a message header, and a message body, where instead of the client currently sending the string that was typed in when the user preses enter, and the server just echoing that back to the clients, you would want to separate the user input with the construction and sending of a high level chat message. The message structure could contain a command or header information to provider the server with routing hints, such as "this message is for all", or "this message is private for a single user". And of course the message body being the string that the user typed in.

For academic purposes such as our assignment, I would also recommend your custom message structure work with XML, to make it human readable, plus there are many good XML parsing API now (I would recommend having a look at StAX) to create simple XML to bean (un)marshaller code.

If you wanted to get some more ideas of what is possible along these lines this, have a look into XMMP (i.e. Jabber). It is an excellent example of a real world chat protocol that has a bunch of these concepts. Their messages are also sent in an XML payload.

There is even an open source Java library implementation of the XMMP (called "smack"), used in the open source Java based server and client, provided by "OpenFire".

bmacampos 09-15-2009 11:25 AM

Hello nicolasd, did you got the private messages working?
I'm doing the same but I had some problems, can you send me your application? bmacampos@hotmail.com
Thanks
BC

linuxraja 09-16-2009 08:53 PM

Go to sourceforge and download a java based chat client ... That could/should be used as ur starting point ...
:)

linux


All times are GMT -5. The time now is 05:42 PM.