N
N
Nikolay Alekseev2020-09-17 07:40:37
C++ / C#
Nikolay Alekseev, 2020-09-17 07:40:37

How to broadcast messages over UDP using Socket?

Good day to all!

The task, it seems to me, is simply incredibly simple, but I didn’t read something somewhere, apparently.
I create a USP server

Socket socket = new Socket( AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp );

Clients connect to it, send something, it slowly listens and reacts to something in a separate thread.
Everything works here.
At some point in time, you need to tell all customers that something happened.
In my naivete, I decided that it is done like this:
public void Send(byte[] data) {
  socket.Send( data , data.Length, SocketFlags.Broadcast);
}

And I get an exception here
SocketException: Предпринятая операция не поддерживается для выбранного типа объекта.


I had a suspicion that the jamb is that the socket is just busy listening at the moment, so it has no time to send. But testing has shown that this is not the case.
I ask for hints: where to dig?

Thank you all in advance for your advice

Answer the question

In order to leave comments, you need to log in

2 answer(s)
N
Nikolai Alekseev, 2020-09-17
@VariusRain

He asked, he answered.
It turns out that it was necessary to read the documentation a little more carefully, although everything is not so obvious there.
Quote from Microsoft website:

If you are using a connectionless protocol in blocking mode, SendTo will block until the datagram is sent. If you want to send data to a broadcast address, you must first call the SetSocketOption method and set the socket option to SocketOptionName.Broadcast . In addition, you must ensure that the number of bytes sent does not exceed the maximum packet size for the underlying service provider. If so, the datagram will not be sent and SendTo will throw a SocketException .

Consequently:
socket.SetSocketOption( SocketOptionLevel.Socket, SocketOptionName.Broadcast, true );

Well, instead of Send, you need to use SendTo, just send it to EndPoint instead of a specific address
IPEndPoint targetEndPoint = new IPEndPoint( IPAddress.Broadcast, 27000 );

A
Alexander Ananiev, 2020-09-17
@SaNNy32

https://stackoverflow.com/questions/40616911/c-sha...

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question