Java Socket - 发送许多消息

时间:2013-09-10 10:49:31

标签: java sockets client-server

我有两个简单的类:

客户端:

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”。 如何在不同时间发送多条消息,只有一个套接字连接?

1 个答案:

答案 0 :(得分:2)

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

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

userInput = stdIn.readLine();

此处,userInput仅等于msg1

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

SERVER:

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
         }
    }

编辑:CLIENT:

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

        out.println(msg1);

        out.println(msg2);

        out.println("END_MSG");
    }

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