我目前正在学习网络,特别是客户端 - 服务器类。 我已经做了大量的研究并实现了各种测试程序,但我无法弄清楚为什么/何时需要使用flush()方法。Java ObjectOutputStream的方法flush()
如果数据总是被输入流读入,怎么会有数据错误地留在输出流中呢?正如客户端 - 服务器代码所指示的那样。 我试图通过省略flush()来测试我的基本回显客户端服务器程序,但我无法打破它。
当通过从客户端写入两次并且只读取一次服务器的回复来测试flush()时,发生的所有事情都是服务器回复中的积压(我假设流类似于队列?)。 然后我采用了相同的代码,并在第二次写入之前和之后添加了flush(),并没有什么区别。就好像flush()并不真正清除流。
那么有人可以请解释什么情况下关于客户端/服务器流交互将冲洗()是必需的?
服务器:
public class ServerApp
{
private ServerSocket listener;
private Socket clientCon;
public ServerApp()
{
try
{
listener = new ServerSocket(1234, 10);
} catch (IOException e)
{
e.printStackTrace();
}
}
public void listen()
{
try
{
System.out.println("Server is listening!");
clientCon = listener.accept();
System.out.println("Server: Connection made with Client");
processClient();
} catch (IOException e)
{
e.printStackTrace();
}
}
public void processClient()
{
try(ObjectOutputStream out = new ObjectOutputStream(clientCon.getOutputStream()); ObjectInputStream in = new ObjectInputStream(clientCon.getInputStream()))
{
String msg;
while(!(msg = (String)in.readObject()).equalsIgnoreCase("Shutdown"))
{
out.writeObject("Server: " + msg);
out.flush();
}
out.writeObject("Server is powering down...");
out.close();
in.close();
} catch (IOException | ClassNotFoundException e)
{
e.printStackTrace();
}
}
public static void main (String args[])
{
ServerApp sa = new ServerApp();
sa.listen();
}
}
客户:
public class ClientApp
{
private Socket serverCon;
public ClientApp()
{
try
{
serverCon = new Socket("127.0.0.1", 1234);
} catch (IOException e)
{
e.printStackTrace();
}
}
public void communicate()
{
try (ObjectOutputStream out = new ObjectOutputStream(serverCon.getOutputStream()); ObjectInputStream in = new ObjectInputStream(serverCon.getInputStream());
BufferedReader br = new BufferedReader(new InputStreamReader(System.in)))
{
String response = null;
do
{
System.out.println("Enter your message for server: ");
out.writeObject(br.readLine());
out.flush();
out.writeObject("Flush not working");
out.flush();
response = (String) in.readObject();
System.out.println(response);
response = (String) in.readObject();
System.out.println(response);
} while (!response.equalsIgnoreCase("Server is powering down..."));
} catch (IOException | ClassNotFoundException e)
{
e.printStackTrace();
}
}
public static void main(String args[])
{
ClientApp ca = new ClientApp();
ca.communicate();
}
}
奇怪的是,当我尝试在ServerApp中使用新的ObjectOutputStream(新的BufferedOutputStream(clientCon.getOutputStream()))时,ClientApp挂起(等待输入并且不输出“输入服务器消息”)。我应该采取的消息形式是,除非使用Buffered流,否则不需要使用flush()? – Shaun