how to disconnect client on a multithread chat

时间:2017-01-15 12:27:08

标签: java multithreading sockets hashmap chat

I want the client to disconnect when I enter the String "disconnect" but I don't understand how I could do it. Also, I need to remove the client from the hashMap so that it will be impossible for the client to send/receive messages. I would appreciate any help I can get on it,been trying to find a solution for a while now but nothing seem to work. here are the Client and server classes:

public class Clientt implements Runnable {//first we implement chat client

//the client socket        //sience we have multiple clients we are implementing threading in our application 
private static Socket clientSocket=null;
//the output stream
private static PrintStream os=null; //initializing the input & output streams
//the input stream
private static BufferedReader br=null;

private static BufferedReader inputLine=null;
private static boolean closed=false;
public static void main(String[]args)
{
    //the default port
    int portNumber=8080;
    //the default host
    String host="localhost";

    if(args.length<2)
    {
        System.out.println("Usage:Java Client <host> <portNumber>\n"
                +"now using host="+host+",portNumber="+portNumber);
    }
    else
    {
        host=args[0];
        portNumber=Integer.valueOf(args[1]).intValue();
    }

    /* 
     * Open a socket on a given host and port.
     * Open input and Output streams
     */

    try{
        clientSocket=new Socket(host,portNumber); //initializing clientsocket with mentioned host and port num
        inputLine=new BufferedReader(new InputStreamReader(System.in));//read input from the user using inputLine
        os=new PrintStream(clientSocket.getOutputStream());//outputstream is used to write to socket
        br=new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));// inputstream is uset to read from socket
    }catch(UnknownHostException e){
        System.err.println("Don't know about host"+host);
    }catch(IOException e) {
        System.err.println("Couldn't get I/O for connection to the host"+host);
      }
    /*
     * If everything has been initialized then we want to write some date 
     * to the socket we have opened a connection to on the port portNumber
     */

    if(clientSocket!=null && os!=null && br!=null)
    {
        try{
            //Creat a thread to read from the server
            new Thread(new Clientt()).start(); //here we implement threading
            while(!closed)
            {
                os.println(inputLine.readLine());//loop continues infinetely untill we terminate application and writes to socket using output stream object
            }
            /*
             * Close the output stream,close the input stream,close the socket
             */
            os.close();
            br.close();
            clientSocket.close();
        }catch(IOException e)
        {
            System.out.println("IOException: "+e);

        }
    }

}

/*
 * Creat thread to read from the server
 * 
 */

//@Override

public void run() {
/*
 * Keep on reading from the socket of the server    
 */
 String responseLine; //used to implement reading from the socket
 try{
     while((responseLine=br.readLine())!=null){ //when we recieve messages we print out here
         System.out.println(responseLine); // "is" is the object of data input stream
     }
     closed=true;
 }catch(IOException e){
     System.out.println("IOException: "+e);
 }


}

}

public class Serverr implements Runnable {//server implements threading by implementing runnable interface
Socket csocket;
static HashMap<Integer,Socket>hm=new HashMap <Integer,Socket>(); //here we store each client socket in hashmap
static int k=1;
Serverr(Socket csocket){
    this.csocket=csocket;//Server ser=new Server(sock); comes here and assigns it to csocket
}

public static void main(String args[])
throws Exception{
    ServerSocket ssock=new ServerSocket(8080);//Socket on port 5000(same as mentioned inclient class)
    System.out.println("Listening");//when connected on port 5000 we print listening
    while(true){
        Socket sock=ssock.accept();//accept client socket
        Serverr ser=new Serverr(sock);//pass socket to constructor of server class
        new Thread(ser).start();//start thread here
        hm.put(k,sock);//add the socket into hashmap
        System.out.println("Connected to client"+k);//print the number of connected client
        PrintWriter out;
        for(int h=1;h<hm.size();h++)//loop through hashmap & get those socket value
        {
            Socket ser1=hm.get(h);

            out=new PrintWriter(ser1.getOutputStream(),true);//we will write to that socket here using outputstream
            out.print("Client "+k+" is connected");
            out.println();//we will get that specific message part 
            out.flush();
        }
        k++;
    }

}
{

}

@Override
public void run() {
    try{
        //once the thread is started we initialize necessary input & output streams here
        PrintWriter out;
        BufferedReader in=new BufferedReader(new InputStreamReader(csocket.getInputStream()));//used to read input from the socket
        String inputLine;
        String j="sending"; //follow a pattern for sending messages
        String l="to";
        String t="sendtoall";//used to sent message to all clients
        String lis="get_users";
        String clos="disconnect";
        while((inputLine=in.readLine())!=null)//if the message from connected client !=null
        {


            String a[]=inputLine.split(" ");//split the input line using space if a[0] is sendmsg and a[2] is to

             if(a[0].equals(j) && a[a.length - 2].equals(l))//we started the server
            {
                 int id=Integer.parseInt(a[a.length - 1]);//we will get the number of client here
                if(hm.containsKey(id)){// we will check hashmap if it contains id
                    Socket ser1=hm.get(id);//here we will get that clients socket from hashmap

                    out=new PrintWriter(ser1.getOutputStream(),true);// we will write to that socket using output stream
                    for (int word = 1; word < a.length - 2; word++ ) {
                        out.print(a[word]+" ");
                    }
                    out.println();//we will get that specific message part 
                    out.flush();// a[1] is...
                }
                else
                {
                    out=new PrintWriter(csocket.getOutputStream(),true);
                    out.println("user offline");//we print it if hashmap doesnt contain the key value
                    out.flush();
                }
            }
             else if(a[0].equals(lis))
                {
                    out=new PrintWriter(csocket.getOutputStream(),true);
                    for(int h=1;h<hm.size();h++)//loop through hashmap & get those socket value
                    {
                          out.print("Client number "+h+"is online");
                    }
                        out.println();//we will get that specific message part 
                        out.flush();
                    }

             else if(a[0].equals(t))//if we want to sent message to all clients at once
            {
                for(int h=1;h<hm.size();h++)//loop through hashmap & get those socket value
                {
                    Socket ser1=hm.get(h);

                    out=new PrintWriter(ser1.getOutputStream(),true);//we will write to that socket here using outputstream
                    for (int word = 1; word < a.length; word++ ) {
                        out.print(a[word]+" ");
                    }
                    out.println();//we will get that specific message part 
                    out.flush();
                }
            }

            else{
                out=new PrintWriter(csocket.getOutputStream(),true);
                out.println("Invalid Message");//if the message format doesnt match
                out.flush();
            }
        }
    }catch(IOException e){
        System.out.println(e);
    }
}

}

0 个答案:

没有答案