我正在从缓冲区读取字符串并将其写入服务器。我遇到的问题是,当我打开套接字并循环写入时,服务器永远不会收到该字符串。
当我使用这个时:
try {
Socket send = new Socket("localhost", 1490);
DataOutputStream out = new DataOutputStream(send.getOutputStream());
String message = null;
while ((message = buffer.get()) != null){
out.writeBytes(message);
}
out.close();
send.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
服务器没有收到该字符串,但是当我这样做时它可以正常工作:
try {
String message = null;
while ((message = buffer.get()) != null){
Socket send = new Socket("localhost", 1490);
DataOutputStream out = new DataOutputStream(send.getOutputStream());
out.writeBytes(message);
out.close();
send.close();
}
} catch (IOException ex) {
ex.printStackTrace();
}
}
显然我不想继续打开和关闭套接字。问题是什么?
每次要发送数据包时,您都需要刷新套接字。
关闭套接字会强制自动刷新,这解释了为什么数据在套接字关闭时发送。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)