简体   繁体   English

等待套接字数据传输

[英]Wait For Socket Data Transmission

I'm using a DataOutputStream to transmit data over the network like this:我正在使用DataOutputStream通过网络传输数据,如下所示:

Socket socket = new Socket(ipAddress, port);
DataOutputStream dataOutputStream = new DataOutputStream(
                    socket.getOutputStream());

dataOutputStream.writeBytes("Stackoverflow");
// ...
System.exit(0);

If my application terminates too early, the transmission will be aborted and therefore fail since not all data has been sent yet at that point.如果我的应用程序过早终止,传输将被中止并因此失败,因为此时尚未发送所有数据。

To fix this, I could manually wait for some time before terminating:为了解决这个问题,我可以在终止之前手动等待一段时间:

try
{
    Thread.sleep(1000);
} catch (InterruptedException e)
{
    e.printStackTrace();
}

However, this solution is bad.但是,这个解决方案很糟糕。 Are there some "best practice" ways of assuring that all data has been sent before terminating my application?是否有一些“最佳实践”方法可以确保在终止我的应用程序之前已发送所有数据?

Edit:编辑:
I don't have access to the server code.我无权访问服务器代码。

If my application terminates too early, the transmission will be aborted and therefore fail since after the execution of flush() not all data has been sent yet.如果我的应用程序过早终止,传输将被中止并因此失败,因为在执行 flush() 之后,尚未发送所有数据。

The data is unbuffered so every write sends the data immediately.数据是无缓冲的,因此每次写入都会立即发送数据。 In your case the flush() isn't doing anything.在您的情况下, flush()没有做任何事情。

DataOutputStream.flush() DataOutputStream.flush()

public void flush() throws IOException {
    out.flush();
}

calls OutputStream.flush()调用 OutputStream.flush()

public void flush() throws IOException {
}

Are there some "best practice" ways of assuring that all data has been sent before terminating my application?是否有一些“最佳实践”方法可以确保在终止我的应用程序之前已发送所有数据?

The best way to ensure the data has been sent is to wait for a reply.确保数据已发送的最佳方法是等待回复。 Have the other end send a message back to say it has received it and you can exit knowing the data has been received.让另一端发回一条消息说它已收到它,您可以退出知道已收到数据。

BTW When you have finished with a closeable resources, best practice is to close it.顺便说一句,当您完成可关闭的资源时,最佳做法是关闭它。

By the default socket.close() should cause graceful TCP connection closing.默认情况下socket.close()应该导致正常的 TCP 连接关闭。 In that procedure TCP stack delivers unacknowledged data to the peer.在该过程中,TCP 堆栈将未确认的数据传送给对等方。

dataOutputStream.flush();
socket.close();

if you have set SO_LINGER to zero, then it won't work.如果您已将 SO_LINGER 设置为零,则它将不起作用。 Alternative is to use socket.shutdownOutput() :另一种方法是使用socket.shutdownOutput()

dataOutputStream.flush();
socket.shutdownOutput();

设置socket.setSendBufferSize(1024)还要确保在那里接收时您以1024字节的块读取。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM