【发布时间】:2016-02-03 10:37:34
【问题描述】:
我目前正在学习网络,特别是客户端-服务器类。 我做了很多研究并实施了各种测试程序,但我无法弄清楚为什么/何时需要使用 flush() 方法。
如果总是被输入流读入,怎么会有数据错误地留在输出流中?正如客户端-服务器代码所指示的那样。 我试图通过省略 flush() 来测试我的基本 echo 客户端服务器程序,但我无法破坏它。
当通过从客户端写入两次并且只读取一次以获取服务器的回复来测试 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();
}
}
【问题讨论】:
标签: java client-server flush objectoutputstream