北城已荒凉 2018-11-11 16:05 采纳率: 0%
浏览 369

服务器只向第一个客户机广播

I'm trying to broadcast a message from a server to all clients, but only one client receives the message.

I want to run this server and two or more instances of this client (taken from Donahoo, Calvert, "TCP/IP Sockets in C", 1e; I can paste the code into this question on request).

The programs work fine with a single client, but when running two clients only one (the first) ever receives a message, while the second instance just gets stuck (on bind).

I don't know what I'm doing wrong, I'm sure the program is correct so perhaps I'm running it wrong. I start the server as:

$ ./BroadcastSender localhost 1337 hey &

As for the clients, I have tried two variations, the first:

$ ./BroadcastReceiver 1337 & ./BroadcastReceiver 1337 &

In the second variation I have added while (1) {} after close(sock) and then run as:

$ ./BroadcastReceiver 1337 &
$ ./BroadcastReceiver 1337 &

Both variations give the same result, namely that the first client receives the message, the other one doesn't, but instead gets stuck trying to bind.

Am I running the server/clients the wrong way, or is there something missing in the code? I'm new to sockets so I don't really see if there's anything in, say, the server code saying "I'm gonna broadcast to one client only".

Could you give me some pointers in the right direction? There are other questions and answers about broadcasting but I haven't found one that addresses this particular issue. Thank you.

转载于:https://stackoverflow.com/questions/53250574/server-broadcasts-only-to-first-client

  • 写回答

1条回答 默认 最新

  • 关注

    you can't have 2 processes bind on the same port. Not familiar with the broadcaster, but generally you have 2 options - either run the 2 processes on 2 machines on the same network or run the clients on separate ports and have the broadcaster broadcast on several ports

    The command line when running 2 processes on 2 machines should be something like:

    $ ./BroadcastSender 127.0.255.255 1337 hey &
    

    when 127.0.255.255 is your subnet mask

    --- edit(thanks @Jeremy) ---

    you can also bind two sockets to the same UDP port using setsockopt with SO_REUSEADDR/SO_REUSEPORT flags

    评论

报告相同问题?

悬赏问题

  • ¥15 树莓派与pix飞控通信
  • ¥15 自动转发微信群信息到另外一个微信群
  • ¥15 outlook无法配置成功
  • ¥30 这是哪个作者做的宝宝起名网站
  • ¥60 版本过低apk如何修改可以兼容新的安卓系统
  • ¥25 由IPR导致的DRIVER_POWER_STATE_FAILURE蓝屏
  • ¥50 有数据,怎么建立模型求影响全要素生产率的因素
  • ¥50 有数据,怎么用matlab求全要素生产率
  • ¥15 TI的insta-spin例程
  • ¥15 完成下列问题完成下列问题