简体   繁体   English

Java - 关闭UDP套接字

[英]Java - closing the UDP socket

I am trying to simulate UDP using Java. 我正在尝试使用Java模拟UDP。 I am sending a file from one host to another. 我正在从一个主机向另一个主机发送文件。 This is the part of the receiver: 这是接收器的一部分:

server.setSoTimeout(10000);     
while (true)
{
    try 
    {
        DatagramPacket received = new DatagramPacket(receivedData,receivedData.length);
        server.receive(received);
        out.write(received.getData());
    } 
    catch (IOException e) {
                break;
            }



    }
server.close();

This solution works, but I am not satisfied with it for some reason. 这个解决方案有效,但由于某些原因我不满意。

Sender sends all the packets and then it closes the DatagramSocket. 发送方发送所有数据包,然后关闭DatagramSocket。 Receiver gets all the packets and it terminates, but it terminates because of the timeout. Receiver获取所有数据包并终止,但由于超时而终止。

So if switch on my receiver and don't execute anything for 10 secs, my Receiver shuts off, so nothing is transmitted. 因此,如果打开我的接收器并且10秒内没有执行任何操作,我的接收器将关闭,因此不会传输任何内容。

Is there a way of terminating the loop without specifying the timeout? 有没有一种方法可以在不指定超时的情况下终止循环?

I was also wondering if there is a method for the other host to establish connection - something like ServerSocket.accept(), which basically waits for the other host to connect.But, I decided to use DatagramSocket and I can't find a solution to this issue. 我还想知道是否有其他主机建立连接的方法 - 比如ServerSocket.accept(),它基本上等待其他主机连接。但是,我决定使用DatagramSocket而我找不到解决方案这个问题。

Does anybody know of a method that would perform this? 有人知道会执行此操作的方法吗?

No. 没有。

Datagram (UDP) sockets are inherently connectionless. 数据报(UDP)套接字本质上是无连接的。 Closing a DatagramSocket does not have any effect which is visible to a remote system. 关闭DatagramSocket没有任何对远程系统可见的影响。 It prevents an application from sending or receiving any further data on that socket, and frees up the port for use by other applications on the local system, but it does not cause any notification to be sent over the network. 它可以防止应用程序在该套接字上发送或接收任何其他数据,并释放该端口以供本地系统上的其他应用程序使用,但不会导致通过网络发送任何通知。

If you want to notify the remote server that you are done sending data, you will need to send them a datagram notifying them of that. 如果要通知远程服务器您已完成发送数据,则需要向它们发送数据报以通知它们。

If you are trying to transfer a file over UDP, keep in mind that UDP packets are not guaranteed to be received, nor are they guaranteed to be received in the same order they are transmitted! 如果您尝试通过UDP传输文件,请记住,不保证收到UDP数据包,也不保证按照传输顺序接收UDP数据包! (That is, they may be dropped or reordered by the network.) (也就是说,它们可能会被网络丢弃或重新排序。)

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

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