何时关闭 UDP 套接字 [英] When to close a UDP socket

查看:46
本文介绍了何时关闭 UDP 套接字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个客户端-服务器应用程序,它使用 UDP 套接字发送数据,数据只需从客户端传输到服务器,并且服务器将始终具有相同的 IP.唯一的要求是我必须每秒发送大约 10 条消息

I have a client-server application that uses a UDP socket to send the data , the data only have to travel from client to server , and the server will always have the same IP. The only requirement is that I have to send messages about 10 messages per second

目前我是这样做的:

public void SendData(byte[] packet)
{
    IPEndPoint end_point = new IPEndPoint(serverIP, serverPort);
    UdpClient udpChannel = new UdpClient(sourcePort);
    udpChannel.Connect(end_point);
    udpChannel.Send(packet, packet.Length);
    udpChannel.Close();
}

我遇到的问题是,当我使用命令udpChannel.Close()"时,服务器未在侦听时需要 2-3 秒才能执行.(我在:如果我不调用 UdpClient.Close() 方法有什么缺点?)

The problem I have is that when I use the command "udpChannel.Close()" it takes 2-3 seconds to be performed when the server is not listening. (I've seen the same problem in: What is the drawback if I do not invoke the UdpClient.Close() method?)

我的问题是,如果我总是将数据包发送到相同的 IP 地址和端口,是否需要在每次发送请求后连接套接字并关闭它?

My question would be, if I always send packets to the same IP address and port, is it necessary to connect the socket and close it after each send request?

我打算使用的代码如下:

The code I intend to use would be as follows:

UdpClient udpChannel;

public void SendData(byte[] packet)
{
    udpChannel.Send(packet, packet.Length);
}

public void Initialize(IPAddress IP, int port)
{
    IPEndPoint end_point = new IPEndPoint(serverIP, serverPort);
    UdpClient udpChannel = new UdpClient(sourcePort);
    udpChannel.Connect(end_point);
}

public void Exit()
{
    udpChannel.Close();
}

这样做,是否有必要在发送数据之前在SendData"方法中做一些检查?上面的代码有问题吗?

Doing it this way, would it be necessary to do some checking in the "SendData" method before sending the data? Is there any problem in the above code?

谢谢!

推荐答案

UDP 是无连接的,调用 udpChannel.Connect 只是指定一个默认的主机端点以与 Send 方法一起使用.您不需要在发送之间关闭客户端,保持打开状态不会在发送之间运行任何连接或侦听器.

UDP is connectionless, calling udpChannel.Connect merely specifies a default host endpoint for use with the Send method. You do not need to close the client between sends, leaving it open will not leave any connections or listeners running between sends.

这篇关于何时关闭 UDP 套接字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆