TUdpSocket Handling

I am trying to use TUdpSocket in Delphi. I want to connect to a UDP server, send some data and wait for a response. The data is sent correctly, but the control does not receive anything. I do not know why. I have been struggling with this problem for many years, and I am going to refuse: - (.

I tried to use TIdUDPClient, but the situation is the same. Data is sent correctly but not accepted.

Only TIdUDPServer works more or less correctly, as it sends and receives data. Unfortunately, data reception is processed by a separate stream (main or different, depending on the ThreadedEvent property), which forces me to use synchronization and complicate the whole code. I would like to handle a UDP connection in my thread. Just send some data and call WaitForData () to wait for a response, and then process it in the same thread.

And if this is not possible, I do not want to use third-party controls, but if this is the only solution, I accept it.

Thank you very much for your help in advance.

---- Examples ---

i) TUDPSocket:

var lR, lW, lE: boolean; begin UdpSocket1.LocalPort := '1600'; UdpSocket1.RemotePort := '1600'; UdpSocket1.RemoteHost := '127.0.0.1'; UdpSocket1.Connect; UdpSocket1.Sendln('test'); UdpSocket1.Select(@lR, @lW, @lE, 2000); if lR then ShowMessage(UdpSocket1.Receiveln()); end; 

As you can see, the control should receive the data that it passes. And apparently this is so, since lR evaluates to true after calling the Select () method. But Receiveln () returns an empty string, as ReceiveBuf () does. When I start the UDP server and send it some data, it is received correctly, so I'm sure that the data is really sent.

+4
source share
2 answers

You do not need anything else:

 function SayHi(Host: String; Port: Integer): String; var Client: TIdUDPClient; begin Client := TIdUDPClient.Create(nil); try Client.Host := Host; Client.Port := Port; Client.Send('Hello'); Result := Client.ReceiveString(1000); finally Client.Free; end; end; 

which in the same stream will send a UDP packet and either receive a UDP packet or raise an exception after a timeout.

If the above does not work, check (using something like Wireshark that the client is really sending data. Then check the server that actually receives the packet.

Send() ultimately (on Windows) calls WinSock sendto() , and ReceiveString() uses select() and recvfrom() . You can sort the TIdUDPServer file with

 while not Terminated do begin S := Client.ReceiveString(1000); DoSomething(S); end; 
+2
source

Another option is to use Synapse for your communication. This is a simple message library that makes blocking calls, so it works well in a single workflow where you want to stop and wait for data, rather than relying on an event to trigger. Recent versions of SVN support the latest versions of Delphi.

0
source

All Articles