如何使服务器可被LAN客户端发现 [英] How to make a server discoverable to LAN clients

查看:52
本文介绍了如何使服务器可被LAN客户端发现的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Socket库进行联网的python多人游戏.该游戏将支持通过LAN进行游戏.一位玩家将设置服务器,LAN上的其他玩家将能够加入游戏.

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

尝试的答案根据汉斯在下面的回答中的建议,可以使用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

这篇关于如何使服务器可被LAN客户端发现的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆