多线程Java客户端服务器问题

时间:2014-04-12 21:51:06

标签: java multithreading

我开发了一个多聊天客户端服务器应用程序,其中One Server将从多个客户端收到的消息广播到所有客户端: 问题是代码不会从以下代码行继续,因此,各个客户端不会从服务器接收消息。 这段代码何时起作用? 此代码仅适用于单个客户端服务器应用程序。

有人可以帮我解决这个应用程序出了什么问题吗?

代码行:

din = new DataInputStream(clientSocketRecv.getInputStream()); 
运行多个客户端时,在MultiClient.java中继续

。 代码如下:

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();
    }
}

}

2 个答案:

答案 0 :(得分:1)

这是我用来测试客户端 - 服务器程序的驱动程序:

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()>>>>>>>>>>>>>>>>>>>>>>>>>>

答案 1 :(得分:0)

  

为什么要创建MultiClient的新对象来启动新线程?

使用

t = new Thread(this);

而不是

t = new Thread(new MultiClient());

MultiClient档案中。


我认为问题出现在MultiClient文件的下面一行。

System.out.println("Reading from the client" + din.readUTF());
while((message = din.readUTF()) != null) {
  • 首先,您已阅读SOP中的行表单客户端。现在您希望将此行转发给客户端,但是while循环中的din.readUTF()的下一次调用将等到客户端再输入一行,因为您已经消耗了SOP中的第一行。请再次检查。
  • 尝试找出线程处于等待状态的位置。

我已在 Client Server communcation 上发布了一些示例。请查看并按照帖子查找更多样本。它将指导您如何在客户端和客户之间进行通信。服务器