How to make a server discoverable to LAN clients

泄露秘密 提交于 2019-12-18 02:55:28

问题


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?


回答1:


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



来源:https://stackoverflow.com/questions/18080094/how-to-make-a-server-discoverable-to-lan-clients

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!