如何使 LAN 客户端可以发现服务器
问题描述
我正在使用 Python 开发一个多人游戏,该游戏使用套接字库进行网络连接.游戏将支持局域网播放.一名玩家将设置服务器,局域网上的其他玩家将能够加入游戏.
I am working on a multiplayer game in python that uses the socket library for its networking. The game will support play over LAN. One player will set up the server and other players on the LAN will be able to join the game.
为了实现这一点,我需要一种让玩家发现可用服务器列表的简单方法(不应该期望玩家必须输入 IP 地址!).我首选的解决方案将仅使用 python 套接字库(以及可选的标准库的其他部分).
To implement this, I need a simple way for the players to discover a list of available servers (players shouldn't be expected to have to enter IP addresses!). My preferred solution would use only the python socket library (and optionally other parts of the standard library).
我正在寻找的是客户端和服务器代码:
What I am looking for is client and server code:
客户端:将其对游戏的请求广播到侦听 LAN 上某个端口的所有机器
client: broadcasts its request for games to all machines listening on a certain port on the LAN
服务器:回复客户端的可用性
server(s): replies to the client with its availability
尝试的答案 按照 Hans 在下面的答案中的建议,可以使用 UDP 套接字来响应来自客户端的广播请求.
ATTEMPTED ANSWER Following Hans' advice in his answer below, a UDP socket can be used to respond broadcast requests from the client.
服务器:
#UDP server responds to broadcast packets
#you can have more than one instance of these running
import socket
address = ('', 54545)
server_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
server_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR,1)
server_socket.bind(address)
while True:
print "Listening"
recv_data, addr = server_socket.recvfrom(2048)
print addr,':',recv_data
server_socket.sendto("*"+recv_data, addr)
客户:
#UDP client broadcasts to server(s)
import socket
address = ('<broadcast>', 54545)
client_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
client_socket.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1)
data = "Request"
client_socket.sendto(data, address)
while True:
recv_data, addr = client_socket.recvfrom(2048)
print addr,recv_data
还有其他令人信服的方法来处理这个可发现性问题吗?
Are there other compelling ways to handle this discoverability problem?
解决方案
你可以试试 UDP 广播.你可以例如从客户端发送广播.然后,服务器应使用其地址广播响应,以便客户端可以使用常规连接.
You could try a UDP broadcast. You can e.g. send a broadcast from the client. The server should then broadcast a response with its address so the client can use a regular connection.
有关示例代码,请参见此处:http://wiki.python.org/moin/UdpCommunication一个>
See here for some example code: http://wiki.python.org/moin/UdpCommunication
相关文章