Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
294 views
in Technique[技术] by (71.8m points)

python - How to make a server discoverable to LAN clients

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.

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:

  • 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

ATTEMPTED ANSWER Following Hans' advice in his answer below, a UDP socket can be used to respond broadcast requests from the client.

Server:

#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)

Client:

#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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.

See here for some example code: http://wiki.python.org/moin/UdpCommunication


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...