简体   繁体   中英

Multithreaded Java Client server issue

I have developed a multi chat client server application in which One Server broadcasts the messages received from Multiple Clients to all the clients : The problem is that the code does not proceed from the following line of code thus, the individual clients do not receive the message back from the server. When does this code work ? This code works only for a single client server application.

Could someone please help me with what is going wrong with this application ?

LINE OF CODE:

din = new DataInputStream(clientSocketRecv.getInputStream()); 

onwards in the MultiClient.java when multiple clients are run. The code is as follows :

Client.java

/**
* 
*/
package Client_Package;

import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;




/**
 * @author sanika
 *
 */

//Client will communicate with the server
public class Client implements Runnable{

private BufferedReader stdIn;
private BufferedReader in;
private  DataInputStream din;
private  DataOutputStream dout;
private static Socket clientSocket;
Thread t;
/**
 * @param args
 */

@Override
public void run() {
    System.out.println("I am in the thread");
    readFromServer();

}


private void readFromServer() {
    try {
        System.out.println("Reading frm server");
        din= new DataInputStream(clientSocket.getInputStream());
        System.out.println("Client Socket value is" + clientSocket);
        System.out.println("Reading from the socket" + din.readUTF());
        while(din.readUTF() != null) {
            System.out.println("Echo from server" + din.readUTF());  
        }
    } catch(IOException ioexp) {

    }

}

private void startClient(BufferedReader stdIn, DataOutputStream dout) {
    String textFromServer = new String();
    String userInput= new String();

    try {
        if((userInput = stdIn.readLine()) != null) {
            //Sent it to the Server
            System.out.println("Sent to the server" + userInput);
            if(userInput.equalsIgnoreCase("Bye")) {
                System.out.println("Client exited");
                System.exit(1);
            }
            System.out.println("Gonna write to the server");
            dout.writeUTF(userInput);
            dout.flush();
        }


    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

}

public static void main(String[] args) {
    // TODO Auto-generated method stub
    String host = args[0];
    int port = Integer.parseInt(args[1]);
    String textFromServer = new String();
    String userInput= new String();
     Client clientObj = new Client();
     if (args.length != 2) {
            System.err.println("Usage: java EchoServer <port number>");
            System.exit(1);
    }


    try {
        clientObj.clientSocket = new Socket(host,port);
        clientObj.dout = new DataOutputStream(clientObj.clientSocket.getOutputStream());
        clientObj.in =  new BufferedReader(new InputStreamReader(clientObj.clientSocket.getInputStream()));
        clientObj.stdIn = new BufferedReader(new InputStreamReader(System.in));

        System.out.println("Thread created!!");
        (new Client()).startClient(clientObj.stdIn,clientObj.dout);
        Thread t = new Thread(new Client());
        t.start();


    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}

}

Server.java

/**
 * 
 */
package Server_Package;

import java.io.BufferedReader;
import java.io.Console;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Vector;

/**
 * @author sanika
 *
 */
 public class Server {

/**
 * @param args
 */
static Vector clientSockets;
public static void main(String[] args) {
    // TODO Auto-generated method stub
    //Accepting input from the console
    int portNumber = Integer.parseInt(args[0]);
    clientSockets = new Vector();
    if (args.length != 1) {
            System.err.println("Usage: java EchoServer <port number>");
            System.exit(1);
    }

    clientSockets = new Vector();
    boolean listening = true; 
    try {
        //while(listening) {
            ServerSocket serverSocket = new ServerSocket(portNumber);
            while(true) {
                MultiClient multiC = new MultiClient(serverSocket.accept(), clientSockets);
            }

    } catch(IOException e) {
        System.out.println("Exception caught when trying to listen to the client port" + portNumber + "or listening for a connection");
        System.out.println(e.getMessage());
    } 


}

}

MultiClient.java

/**
* 
*/
package Server_Package;

import java.io.BufferedReader;
import java.io.Console;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
import java.nio.channels.SocketChannel;
import java.util.Vector;

/**
 * @author sanika
 * 
*/
public class MultiClient implements Runnable {

private Socket clientSocket;
private static int count = 0;
private DataOutputStream dout;
private DataInputStream din;
static Vector clientSockets;
private Thread t;
public MultiClient() {

}

public MultiClient(Socket clientSocket, Vector clientSockets) {
    System.out.println("Came into the MultiClient constructor");
    this.clientSocket = clientSocket;
    this.clientSockets = clientSockets;
    try {
         t = new Thread(new MultiClient());

        System.out.println("Added this socket to the list in MultiChatClient" + this.clientSocket);

        clientSockets.add(this.clientSocket);
        t.start();

    } catch (Exception e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}

@Override
public void run() {

    try {
        //dout = new DataOutputStream(this.clientSocket.getOutputStream());
        //din = new DataInputStream(this.clientSocket.getInputStream());
        DataOutputStream tdout= null;
        String inputLine="";
        System.out.println("Came into the run method in the MultiCHatClient class");
        count++;
        System.out.println("The clientSockets size" + clientSockets.size());

        for(int i=0; i < clientSockets.size() ; i++) {
                    //Assigned a new Socket to each client to initiate data transfer

                    Socket clientSocketRecv = (Socket)(clientSockets.get(i));
                    System.out.println("Client Socket" + clientSocketRecv);

                    din = new DataInputStream(clientSocketRecv.getInputStream());
                    String message= null;
                    System.out.println("Reading from the client" + din.readUTF());
                    while((message = din.readUTF()) != null) {
                        this.dout = new DataOutputStream(clientSocketRecv.getOutputStream());
                        System.out.println("From Server" + "For Client" + count + message);
                        this.dout.writeUTF("From Server" + "For Client" + count + message);
                        this.dout.flush();
                        } 

                }



    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}

}

Here's a driver I use for testing client - server programs:

public static void main(final String[] args) {
  Thread t1 = new Thread(new Runnable() {
     public void run() {
        try{Server.main(new String[]{"8080"});}catch(Exception x){x.printStackTrace();}
     }
  });
  t1.start();

  try{Thread.sleep(100);}catch(Exception x){}

  Thread t2 = new Thread(new Runnable() {
     public void run() {
        try{Client.main(new String[]{"127.0.0.1", "8080"});}catch(Exception x){x.printStackTrace();}
     }
  });
  t2.start();

  Thread t3 = new Thread(new Runnable() {
     public void run() {
        try{Client.main(new String[]{"127.0.0.1", "8080"});}catch(Exception x){x.printStackTrace();}
     }
  });
  t3.start();

  // wait and exit  Change time to suit -To catch runaway code
  try{Thread.sleep(5000);}catch(Exception x){}
  System.out.println("Exiting main");
  System.exit(0);

}  //  end main()>>>>>>>>>>>>>>>>>>>>>>>>>>

Why are you creating a new object of MultiClient to start a new thread?

Use

t = new Thread(this);

instead of

t = new Thread(new MultiClient());

in MultiClient file.


I think the problem is at below lines in MultiClient file.

System.out.println("Reading from the client" + din.readUTF());
while((message = din.readUTF()) != null) {
  • First you have read the line form client in SOP. Now you are expecting to forward this line to client back but the next call of din.readUTF() in while loop will wait till client enters one more line because you have already consumed first line in SOP. Please check it again.
  • Try to find it out that where is thread in waiting state.

I have posted some samples on Client Server communcation . Please have a look and follow the post to find out more samples. It will guide you how to communicate between client & server.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM