Java服务器-客户端readLine()方法 [英] Java server-client readLine() method

查看:98
本文介绍了Java服务器-客户端readLine()方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have a client class and a server class. If client sends message to server, server will send response back to the client, then client will print all the messages it received.

例如,

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

If Client sends "A" to Server, then Server will send response to client "1111". So I use readLine() in client class to read the message from server, then client print "1111" in the console.

如果客户端将 B发送到服务器,然后服务器将响应发送到客户端
2222\n 3333。因此,客户端的预期打印输出为:

If Client sends "B" to Server, then Server will send response to client "2222\n 3333". So the expected printing output from client is:

2222

3333

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

So the response message from server to client may have 1 line or 2 lines depending on the message it send from client to server.

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

My question is that how I can use readLine() to read the message that send from server to client. More specifically, if I use the following codes,

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

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

It will only print the first line, and will not print anything else even if I keep sending message from client to server, because readLine() will stops once it has read the first line.

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

update: More specifically, I am looking for some methods in the client class to read message that contains 1 or multiple lines from server at a time. I am wondering if there are any ways to do it in client side if I don't want to change the format of the message that sent from server to client.

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

update 2 To make my question more clear, I will put some sample codes in the following:

这是服务器:

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


推荐答案


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

You shouldn't need to change the format of the data sent by the server, and readLine() should work, but I suspect that the server is not flushing or closing the OutputStream after writing the response which could possibly explain things.
Is the call to readLine() hanging? Are you in control of the server code? If so, can you include it?

经修订的类可以按您的预期工作:

Revised classes that work as I believe you expect:

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

这篇关于Java服务器-客户端readLine()方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆