斗士狗 2018-11-11 16:05 采纳率: 0%
浏览 390

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

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条回答 默认 最新

  • perhaps? 2018-11-11 16:14
    关注

    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 eclipse运行项目时遇到的问题
  • ¥15 关于#c##的问题:最近需要用CAT工具Trados进行一些开发
  • ¥15 南大pa1 小游戏没有界面,并且报了如下错误,尝试过换显卡驱动,但是好像不行
  • ¥15 没有证书,nginx怎么反向代理到只能接受https的公网网站
  • ¥50 成都蓉城足球俱乐部小程序抢票
  • ¥15 yolov7训练自己的数据集
  • ¥15 esp8266与51单片机连接问题(标签-单片机|关键词-串口)(相关搜索:51单片机|单片机|测试代码)
  • ¥15 电力市场出清matlab yalmip kkt 双层优化问题
  • ¥30 ros小车路径规划实现不了,如何解决?(操作系统-ubuntu)
  • ¥20 matlab yalmip kkt 双层优化问题