MultiCast Messages to multiple clients on the same machine

后端 未结 5 1831
醉话见心
醉话见心 2021-02-14 10:34

Im trying to write a server/service that broadcasts a message on the lan ever second or so, Kind of like a service discovery.

The message needs to be rece

5条回答
  •  Happy的楠姐
    2021-02-14 11:00

    It's definitely possible.

    Re "UDP or multicast", you're talking apples and oranges. Multicast is an IP concept, so you can happily UDP over multicast IP, or over broadcast IP.

    If you're OK with the limitation of having all the clients link-local (routers etc. generally don't forward broadcast packets), I'd say just go with broadcast. TIdUdpBase.Broadcast will be your friend here.

    Update: With either multicast or broadcast, you can only have one socket bound to any particular IP/port pair. Thus, if you want multiple clients all listening to the SAME broadcast/multicast, I think you will need an extra dispatcher client. This dispatcher client receives broadcasts and notifies every client on the machine.

    Within each of your clients you have a little registration procedure that says "Try bind to the port to which broadcasts are sent. If you can, set up a dispatcher client on that port. If you can't, the dispatcher's already created, and register yourself to that dispatcher."

    That registration process could be as simple as binding to any available port on the localhost IP, and saying to the dispatcher "Please send broadcasts to this IP/port."

    Update: Christopher Chase has the right idea. I just finished almost the exact same solution as his, except I patched IdIPMCastClient, adding a property ReuseAddr: Boolean and changing TIdIPMCastClient.GetBinding by adding

    if Self.ReuseAddr then begin
      SetReuseAddr := Id_SO_True;
      Bindings[i].SetSockOpt(Id_SOL_SOCKET, Id_SO_REUSEADDR, @SetReuseAddr, Sizeof(SetReuseAddr));
    end;
    

    between the calls to AllocateSocket and Bind (where SetReuseAddr: Integer).

提交回复
热议问题