2

我有一个客户端类和一个服务器类。如果客户端向服务器发送消息,服务器会将响应发送回客户端,然后客户端将打印它收到的所有消息。

例如,

如果客户端向服务器发送“A”,那么服务器将向客户端“1111”发送响应。所以我在客户端类中使用 readLine() 从服务器读取消息,然后客户端在控制台中打印“1111”。

如果客户端向服务器发送“B”,那么服务器将向客户端“2222\n 3333”发送响应。所以客户端的预期打印输出是:

“2222”

“3333”

因此,从服务器到客户端的响应消息可能有 1 行或 2 行,具体取决于它从客户端发送到服务器的消息。

我的问题是如何使用 readLine() 来读取从服务器发送到客户端的消息。更具体地说,如果我使用以下代码,

String messageFromServer;
while(( messageFromServer = inputStreamFromServer.readLine()) != null) {
    println(messageFromServer);
}

它只会打印第一行,即使我继续从客户端向服务器发送消息也不会打印任何其他内容,因为 readLine() 将在读取第一行后停止。

更新: 更具体地说,我正在客户端类中寻找一些方法来一次读取包含来自服务器的 1 行或多行的消息。如果我不想更改从服务器发送到客户端的消息格式,我想知道是否有任何方法可以在客户端执行此操作。

更新2 为了让我的问题更清楚,我将在下面放置一些示例代码:

这是服务器:

import java.net.*;
import java.io.*;

public class Server {
 public static void main(String[] args) throws IOException {

  ServerSocket serverSocket = null;
  try {
    serverSocket = new ServerSocket(1234);
} catch (IOException e) {
    System.err.println("Could not listen on port: 1234.");
    System.exit(1);
}

Socket clientSocket = null;
try {
    clientSocket = serverSocket.accept();
} catch (IOException e) {
    System.err.println("Accept failed.");
}
 System.out.println("Connected");


PrintWriter out = new PrintWriter(clientSocket.getOutputStream(), true);
BufferedReader in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));

String textFromClient =null;
String textToClient =null;
textFromClient = in.readLine(); // read the text from client
if( textFromClient.equals("A")){
   textToClient = "1111";
}else if ( textFromClient.equals("B")){
   textToClient = "2222\r\n3333";
}


out.print(textToClient + "\r\n");  // send the response to client
 out.flush();
 out.close();
 in.close();
 clientSocket.close();
 serverSocket.close();
 }
}

客户端:

public class Client {
public static void main(String[] args) throws IOException {

    Socket socket = null;
    PrintWriter out = null;
    BufferedReader in = null;
    BufferedReader read = new BufferedReader(new InputStreamReader(System.in));
    try {
        socket = new Socket("localhost", 1234);
        out = new PrintWriter(socket.getOutputStream(), true);
        in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
    } catch (UnknownHostException e) {
        System.err.println("Don't know about host");
    } catch (IOException e) {
        System.err.println("Couldn't get I/O for the connection");
    }
    System.out.println("Connected");

    String textToServer;

    while((textToServer = read.readLine())!=null){
        out.print(textToServer + "\r\n" );  // send to server
        out.flush();

        String messageFromServer =null;
        while(( messageFromServer = textToServer=in.readLine()) != null){
            System.out.println(messageFromServer);
        }
    }
    out.close();
    in.close();
    read.close();
    socket.close();
}

private static void debug(String msg)
{
    System.out.println("Client: " + msg);
}
 }
4

3 回答 3

2

您不需要更改服务器发送的数据的格式,并且 readLine() 应该可以工作,但我怀疑服务器在编写可能解释事情的响应后没有刷新或关闭 OutputStream。
对 readLine() 的调用是否挂起?你在控制服务器代码吗?如果是这样,你能包括它吗?

修改后的课程按我的预期工作:

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;

public class ClientServerTest2
{

    public static void main(String[] args) throws Exception
    {
        Thread serverThread = new Thread(new Server());
        serverThread.start();
        Thread clientThread = new Thread(new Client());
        clientThread.start();

        serverThread.join();
        clientThread.join();
    }

    private static class Server implements Runnable
    {
        @Override
        public void run()
        {
            ServerSocket serverSocket = null;
            try
            {
                serverSocket = new ServerSocket(1234);

                Socket clientSocket = null;
                clientSocket = serverSocket.accept();
                debug("Connected");

                PrintWriter out = new PrintWriter(clientSocket.getOutputStream(), true);
                BufferedReader in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));

                String textFromClient = null;
                String textToClient = null;
                textFromClient = in.readLine(); // read the text from client
                debug("Read '" + textFromClient + "'");
                if ("A".equals(textFromClient))
                {
                    textToClient = "1111";
                }
                else if ("B".equals(textFromClient))
                {
                    textToClient = "2222\r\n3333";
                }

                debug("Writing '" + textToClient + "'");
                out.print(textToClient + "\r\n"); // send the response to client
                out.flush();
                out.close();
                in.close();
                clientSocket.close();
                serverSocket.close();
            }
            catch (Exception e)
            {
                e.printStackTrace();
            }

        }

        private static void debug(String msg)
        {
            System.out.println("Server: " + msg);
        }
    }

    private static class Client implements Runnable
    {

        @Override
        public void run()
        {
            Socket socket = null;
            PrintWriter out = null;
            BufferedReader in = null;
            BufferedReader read = new BufferedReader(new InputStreamReader(System.in));
            try
            {
                socket = new Socket("localhost", 1234);
                out = new PrintWriter(socket.getOutputStream(), true);
                in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
                debug("Connected");

                String textToServer;

                textToServer = read.readLine();
                debug("Sending '" + textToServer + "'");
                out.print(textToServer + "\r\n"); // send to server
                out.flush();

                String serverResponse = null;
                while ((serverResponse = in.readLine()) != null)
                    debug(serverResponse); // read from server and print it.

                out.close();
                in.close();
                read.close();
                socket.close();
            }
            catch (IOException e)
            {
                e.printStackTrace();
            }
        }
    }

    private static void debug(String msg)
    {
        System.out.println("Client: " + msg);
    }
}
于 2013-03-18T16:52:58.457 回答
0

更改while(( messageFromServer = inputStreamFromServer.readLine() != null)while(( messageFromServer = inputStreamFromServer.readLine()) != null)

实际上这甚至不应该编译....

于 2013-03-18T16:02:46.000 回答
0

这是一个解决方法。

如果您想发送多个字符串,例如:“2222\n 3333”。

您可以通过在两个字符串之间添加分隔符(如:)来发送它们: “2222 3333”。

然后你可以从服务器端调用 write 作为

clientOut.write("2222: 3333\n");

在客户端解析收到的字符串:

messageFromServer = inputStreamFromServer.readLine();
String strArray[] = messageFromServer.split(":");

strArray[0] : 2222

strArray[0] : 3333
于 2013-03-18T16:05:28.363 回答