客户端和服务器套接字连接 - 如何向客户端发送ID

时间:2014-05-08 18:37:41

标签: java sockets

我有一台连接到两个客户端的服务器,我希望将消息从一个发送到另一个,一次只有一个客户端处于活动状态,因此在发送每个消息后,它等待来自另一个客户端的响应。因此,客户端应该知道它需要做的第一件事是将消息写入第二个客户端还是等待来自第一个客户端的消息。

这是我项目的服务器端:

public void connect() throws IOException {
    log(TA, "ServerSocket created. \nListering for connections...\n");
    server = new ServerSocket(port, 2);

    conn1 = server.accept();
    output1 = new PrintWriter(conn1.getOutputStream());
    input1 = new BufferedReader(new InputStreamReader(
            conn1.getInputStream()));
    log(TA, "User " + 1 + " connected.\n");
    output1.println("1");

    conn2 = server.accept();
    output2 = new PrintWriter(conn2.getOutputStream());
    input2 = new BufferedReader(new InputStreamReader(
            conn2.getInputStream()));
    log(TA, "User " + 2 + " connected.\n");
    output2.println("2");
    while (true) {
        String text = input1.readLine();

            TA.append("Player 1: " + text + "\n");
            output2.println("Player 1: " + text);

        text = input2.readLine();

            TA.append("Player 2: " + text + "\n");
            output1.println("Player 2: " + text);
    }

}

这是客户:

private static void connect() throws IOException {
    conn = new Socket("192.168.0.25", port);
    TA.append("Socket created.\n");
    out = new PrintWriter(conn.getOutputStream(), true);
    in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
    TA.append("Streams created.\n");
    String inputLine;
    while ((inputLine = in.readLine()) != null)
    player_number = Integer.parseInt(inputLine);
    TA.append("Your ID is " + player_number + " .");
}

public void actionPerformed(ActionEvent evt) {
    String text = TF.getText();
    TA.append("Me: " + text + "\n");
    TF.selectAll();
    TA.setCaretPosition(TA.getDocument().getLength());
    if (player_number == 2)
        try {
            TA.append("Player 1: " + in.readLine());
        } catch (IOException e1) {
            e1.printStackTrace();
        }
    out.println(text);
    if (player_number == 1)
        try {
            TA.append("Player 2: " + in.readLine());
        } catch (IOException e1) {
            e1.printStackTrace();
        }

}

它应该做的是,一旦连接到一个客户端,服务器应该让它知道它的第一个或第二个,并且客户端应该" aknowledge"通过写"Your ID is " + player_number + " ."来写。这应该在我向任一文本字段输入任何内容之前发生。但是现在发生了什么,我启动服务器和两个客户端,只在客户端上发送"Streams created"消息,当我从第一个客户端发送内容时,它显示在服务器的textarea中,但不在另一个客户端中。客户端我从冻结中发送消息。

这与parseInt部分有关,因为该程序停止了,但我不知道原因。

0 个答案:

没有答案