简体   繁体   English

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

[英]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. 当多个客户端运行时,从MultiClient.java开始。 The code is as follows : 代码如下:

Client.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 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 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? 为什么要创建MultiClient的新对象以启动新线程?

Use 采用

t = new Thread(this);

instead of 代替

t = new Thread(new MultiClient());

in MultiClient file. MultiClient文件中。


I think the problem is at below lines in MultiClient file. 我认为问题出在MultiClient文件的以下MultiClient行。

System.out.println("Reading from the client" + din.readUTF());
while((message = din.readUTF()) != null) {
  • First you have read the line form client in SOP. 首先,您已经阅读了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. 现在,您希望将该行转发回客户端,但是while循环中的din.readUTF()的下一次调用将等到客户端再输入一行,因为您已经在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. 它将指导您如何在客户端和服务器之间进行通信。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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