Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/363.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/multithreading/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
java多线程的多客户端错误_Java_Multithreading_Client_Chat - Fatal编程技术网

java多线程的多客户端错误

java多线程的多客户端错误,java,multithreading,client,chat,Java,Multithreading,Client,Chat,下面是处理多用户聊天的客户端和服务器的代码。但当一个客户端写退出我的其他客户端时,当前连接的客户端也会终止,我无法连接另一个客户端。有人能帮忙吗 这是我的客户代码: class TCPClientsc { public static void main(String argv[]) throws Exception { String modifiedSentence; InetAddress inetAddress = InetAddress.getLoc

下面是处理多用户聊天的客户端和服务器的代码。但当一个客户端写退出我的其他客户端时,当前连接的客户端也会终止,我无法连接另一个客户端。有人能帮忙吗

这是我的客户代码:

class TCPClientsc {
    public static void main(String argv[]) throws Exception {
        String modifiedSentence;
        InetAddress inetAddress = InetAddress.getLocalHost();
        System.out.println(inetAddress);

        Socket clientSocket = new Socket(inetAddress, 6789);
        DataOutputStream outToServer = new DataOutputStream(clientSocket.getOutputStream());

        BufferedReader inFromServer = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));

        CThread write = new CThread(inFromServer, outToServer, 0, clientSocket);
        CThread read = new CThread(inFromServer, outToServer, 1, clientSocket);
    }
}

class CThread extends Thread {
    BufferedReader inFromServer;
    DataOutputStream outToServer;
    Socket clientSocket = null;
    int RW_Flag;
    public CThread(BufferedReader in, DataOutputStream out, int rwFlag, Socket clSocket) {
        inFromServer = in;
        outToServer = out;
        RW_Flag = rwFlag;
        clientSocket = clSocket;
        start();
    }
    public void run() {
        String sentence;
        try {
            while (true) {
                if (RW_Flag == 0) {// write
                    BufferedReader inFromUser = new BufferedReader(new InputStreamReader(System.in));
                    sentence = inFromUser.readLine();

                    // System.out.println("Writing ");
                    outToServer.writeBytes(sentence + '\n');
                    if (sentence.equals("quit"))
                        break;

                } else if (RW_Flag == 1) {
                    sentence = inFromServer.readLine();
                    if (sentence.endsWith("quit"))
                        break;
                    System.out.println("(received)" + sentence);
                }
            }
        } catch (Exception e) {
        } finally {
            try {
                inFromServer.close();
                outToServer.close();
                clientSocket.close();

            } catch (IOException ex) {
                Logger.getLogger(CThread.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
    }
}
服务器代码:

class TCPServersc {
    static int i = 0;
    static SThread tt[] = new SThread[100];
    static SThread anot[] = new SThread[100];
    public static void main(String argv[]) throws Exception {
        String client;
        String capitalizedSentence;
        ServerSocket welcomeSocket = new ServerSocket(6789);

        while (true) {
            Socket connectionSocket = welcomeSocket.accept();
            i++;
            System.out.println("connection :" + i);
            BufferedReader inFromClient = new BufferedReader(newInputStreamReader(connectionSocket.getInputStream()));
            DataOutputStream outToClient = new DataOutputStream(connectionSocket.getOutputStream());
            BufferedReader inFromMe = new BufferedReader(new InputStreamReader(System.in));

            tt[i] = new SThread(inFromClient, outToClient, tt, 0, connectionSocket, i);
            anot[i] = new SThread(inFromMe, outToClient, tt, 1, connectionSocket, i);
        }
    }
}

// ===========================================================
class SThread extends Thread {
    BufferedReader inFromClient;
    DataOutputStream outToClient;
    String clientSentence;
    SThread t[];
    String client;
    int status;
    Socket connectionSocket;
    int number;

    public SThread(BufferedReader in, DataOutputStream out, SThread[] t, int status, Socket cn, int number) {
        inFromClient = in;
        outToClient = out;
        this.t = t;
        this.status = status;
        connectionSocket = cn;
        this.number = number;
        start();
    }

    public void run() {
        try {
            if (status == 0) {
                clientSentence = inFromClient.readLine();
                StringTokenizer sentence = new StringTokenizer(clientSentence, " ");

                // ///////////////////////////////////////////////////////////
                if (sentence.nextToken().equals("login")) {
                    String user = sentence.nextToken();
                    String pass = sentence.nextToken();
                    FileReader fr = new FileReader("file.txt");
                    BufferedReader br = new BufferedReader(fr);
                    int flag = 0;
                    while ((client = br.readLine()) != null) {
                        if ((user.equals(client.substring(0, 5))) && (pass.equals(client.substring(6, 10)))) {
                            flag = 1;
                            System.out.println(user + " has logged on");
                            for (int j = 1; j <= 20; j++) {
                                if (t[j] != null)
                                    t[j].outToClient.writeBytes(user + " has logged on" + '\n');// '\n' is necessary
                            }
                            break;
                        }
                    }
                    if (flag == 1) {
                        while (true) {
                            clientSentence = inFromClient.readLine();
                            System.out.println(user + " : " + clientSentence);
                            for (int j = 1; j <= 20; j++) {
                                if (t[j] != null)
                                    // '\n' is necessary
                                    t[j].outToClient.writeBytes(user + " : " + clientSentence + '\n');
                            }
                            // if(clientSentence.equals("quit"))break;
                        }
                    }
                }
            }
            // /////////////////////////////////////////////////////////////////////////////////////////////////////////////////
            if (status == 1) {
                while (true) {
                    clientSentence = inFromClient.readLine();
                    if (clientSentence.equals("quit"))
                        break;

                    System.out.println("Server: " + clientSentence);
                    for (int j = 1; j <= 20; j++) {
                        if (t[j] != null)
                            t[j].outToClient.writeBytes("Server :" + clientSentence + '\n');// '\n' is necessary
                    }
                }
            }
        } catch (Exception e) {
        } finally {
            try {
                // System.out.println(this.t);
                inFromClient.close();
                outToClient.close();
                connectionSocket.close();
            } catch (IOException ex) {
                Logger.getLogger(SThread.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
    }
}

这段代码有很多问题

首先,在将来,请发布更小、简洁、格式良好的代码片段。我只是需要基本上重新格式化你帖子中的所有内容。 我看到有几个地方你正在抓捕,但除了例外什么也没做。这是非常糟糕的做法。至少您应该打印/记录捕获的异常。我怀疑这是造成你问题的原因。 我发现RW_标志非常混乱。那么您应该有两个客户端线程。一个用于从System.in写入服务器,另一个用于读取。没有一个客户端线程可以做两件事。与服务器中的状态标志相同。这应该是两个不同的线程。 而不是int标志=0;在服务器中,应该是布尔loggedIn;。在Java中使用布尔值而不是C样式的标志,并使用更好的变量名。代码的可读性是值得的。状态、RW_标志等相同。。 您应该将连续的代码移出方法,而不是庞大的代码块:handleSystemIn、handleClient、talkToServer。一旦您在代码中创建了更多的方法,并缩小了各个代码块,它将使代码更具可读性/可调试性/可理解性。 您需要在该阵列的每次使用周围有一个同步的tt块。一旦有多个线程都在使用tt,如果主accept线程添加了tt,则需要同步更新。
虽然spagetti代码太难解析,但我没有立即发现问题。我怀疑你在某个地方抛出了异常和异常,这就是为什么第一个客户端退出后无法连接的原因。除此之外,我将继续自由使用System.out.println调试来查看哪些消息被发送到何处。

可能问题出在服务器上,而不是客户端,因为一个客户端可能会影响另一个客户端。我们必须查看服务器代码。请将代码格式化为可读的格式,并删除注释掉的语句。如果你要求别人花时间阅读你的代码,你应该愿意让它可读。我们不想费力阅读你丰富且格式糟糕的代码。减少它并格式化它,那么您可能有机会