Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When to close a UDP socket

Tags:

c#

sockets

udp

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

Currently I am doing it the following way :

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();
}

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?)

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();
}

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?

Thank you!

like image 307
Josep B. Avatar asked Nov 06 '13 18:11

Josep B.


1 Answers

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.

like image 161
Ashigore Avatar answered Sep 20 '22 21:09

Ashigore