簡體   English   中英

多線程Java客戶端服務器問題

[英]Multithreaded Java Client server issue

我已經開發了一個多聊天客戶端服務器應用程序,其中一個服務器將從多個客戶端接收的消息廣播到所有客戶端:問題是該代碼沒有從下面的代碼行繼續進行,因此,各個客戶端都沒有收到該消息。從服務器返回。 該代碼什么時候起作用? 此代碼僅適用於單個客戶端服務器應用程序。

有人可以幫助我解決此應用程序的問題嗎?

代碼行:

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

}

這是我用於測試客戶端-服務器程序的驅動程序:

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

為什么要創建MultiClient的新對象以啟動新線程?

采用

t = new Thread(this);

代替

t = new Thread(new MultiClient());

MultiClient文件中。


我認為問題出在MultiClient文件的以下MultiClient行。

System.out.println("Reading from the client" + din.readUTF());
while((message = din.readUTF()) != null) {
  • 首先,您已經閱讀了SOP中的線路表單客戶端。 現在,您希望將該行轉發回客戶端,但是while循環中的din.readUTF()的下一次調用將等到客戶端再輸入一行,因為您已經在SOP中使用了第一行。 請再次檢查。
  • 嘗試找出線程在等待狀態。

我已經在客戶端服務器通信中發布了一些示例。 請看一下,並按照該帖子查找更多示例。 它將指導您如何在客戶端和服務器之間進行通信。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM