1

我有两个简单的类:

客户:

public static void main(String[] args) throws IOException {
        InetAddress addr = InetAddress.getByName(null);
        Socket socket = null;

        try {
            socket = new Socket(addr, 1050);

            InputStreamReader isr = new InputStreamReader(socket.getInputStream());
            in = new BufferedReader(isr);

            OutputStreamWriter osw = new OutputStreamWriter( socket.getOutputStream());
            BufferedWriter bw = new BufferedWriter(osw);
            out = new PrintWriter(bw, false);

            stdIn = new BufferedReader(new InputStreamReader(System.in));
            String userInput;

            // read user input
            while (true) {
                userInput = stdIn.readLine();

                System.out.println("Send: " + userInput);
                out.println(userInput);
                out.flush();

                String line = in.readLine();
                while(line != null){
                    System.out.println(line);
                    line = in.readLine();
                }

                System.out.println("END");
            }
        }
        catch (UnknownHostException e) {
            // ...
        } catch (IOException e) {
            // ...
        }

        // close
        out.close();
        stdIn.close();
        socket.close();
    }

服务器:

OutputStreamWriter osw = new OutputStreamWriter(socket.getOutputStream());
                BufferedWriter bw = new BufferedWriter(osw);
                PrintWriter out = new PrintWriter(bw, /*autoflush*/true);
private void sendMessage(String msg1, String msg2) {
        out.println(msg1);

        // empy row
        out.println("");

        out.println(msg2);
    }

用户输入一条消息,并将其发送到服务器。然后,服务器响应 N 条消息。在第一次请求之后,客户端停止并且永远不会打印单词“END”。如何在不同时间发送多条消息,只有一个套接字连接?

4

1 回答 1

2

首先,您不需要发送空行,因为您是通过“line”发送并通过“line”接收。

out.println(msg1);
out.println(msg2);

userInput = stdIn.readLine();

在这里,userInput将只等于msg1

我建议不要循环stdIn.readLine() = null,而是让客户端发送,例如“END_MSG”,以通知服务器它将不再发送消息。也许像...

服务器:

userInput =stdIn.readLine();
if(userInput.Equals("START_MSG");
    boolean reading=true;
    while(reading)
    {
         userInput=stdIn.readLine();
         if(userInput.Equals("END_MSG")
         {
             //END LOOP!
             reading = false;
         }
         else
         {
             //You have received a msg - do what you want here
         }
    }

编辑:客户:

private void sendMessage(String msg1, String msg2) {
        out.println("START_MSG");

        out.println(msg1);

        out.println(msg2);

        out.println("END_MSG");
    }

(在您的问题中看起来还混淆了客户端和服务器?)

于 2013-09-10T11:11:57.433 回答