问题
Its my first time programing network in java. I was looking for a way to send to somehow broadcast to all nodes in the whole networking. To let them know of my existence. I'm trying to make a multiplayer network game, and I want the clients to be able to see all the games available to choose which one to join. I want to know how to broadcast from the server and also how to make the clients listen.
Please make it simple, I'm a newbie :)
Thanks in advance.
回答1:
To broadcast data packets, send them to the broadcast address of the given subnet (the last address of the subnet). The IP 255.255.255.255
is the broadcast address for the zero network.
A special definition exists for the IP broadcast address 255.255.255.255. It is the broadcast address of the zero network or 0.0.0.0, which in Internet Protocol standards stands for this network, i.e. the local network. Transmission to this address is limited by definition, in that it is never forwarded by the routers connecting the local network to the Internet.
Broadcast address
So to broadcast to your current network, send the packets to 255.255.255.255
.
回答2:
Do not confuse terms.
Broadcast is usually used for UDP. UDP is unreliable in the sense that it does not check if all of the packets are received by the clients. Opening a lot of TCP connections to a lot of clients is not broadcast.
To have your clients listen to a port, you need to use ServerSocket and read it.
回答3:
I recommend that you use PubSubHubbub or a similar protocol. Basically, you would have a "hub" to which you send the notification that you want to have "broadcasted". Each of the nodes subscribes to the topic, by providing a URL that the hub can invoke when new data has arrived. When the "hub" receives this broadcast, the hub contacts each subscription URL to let the node know there is new data.
来源:https://stackoverflow.com/questions/6568446/how-to-broadcast-in-java-network