問題描述
我正在使用 Python 開發(fā)一個多人游戲,該游戲使用套接字庫進(jìn)行網(wǎng)絡(luò)連接.游戲?qū)⒅С志钟蚓W(wǎng)播放.一名玩家將設(shè)置服務(wù)器,局域網(wǎng)上的其他玩家將能夠加入游戲.
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.
為了實現(xiàn)這一點,我需要一種讓玩家發(fā)現(xiàn)可用服務(wù)器列表的簡單方法(不應(yīng)該期望玩家必須輸入 IP 地址!).我首選的解決方案將僅使用 python 套接字庫(以及可選的標(biāo)準(zhǔn)庫的其他部分).
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).
我正在尋找的是客戶端和服務(wù)器代碼:
What I am looking for is client and server code:
客戶端:將其對游戲的請求廣播到偵聽 LAN 上某個端口的所有機(jī)器
client: broadcasts its request for games to all machines listening on a certain port on the LAN
服務(wù)器:回復(fù)客戶端的可用性
server(s): replies to the client with its availability
嘗試的答案 按照 Hans 在下面的答案中的建議,可以使用 UDP 套接字來響應(yīng)來自客戶端的廣播請求.
ATTEMPTED ANSWER Following Hans' advice in his answer below, a UDP socket can be used to respond broadcast requests from the client.
服務(wù)器:
#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
還有其他令人信服的方法來處理這個可發(fā)現(xiàn)性問題嗎?
Are there other compelling ways to handle this discoverability problem?
推薦答案
你可以試試 UDP 廣播.你可以例如從客戶端發(fā)送廣播.然后,服務(wù)器應(yīng)使用其地址廣播響應(yīng),以便客戶端可以使用常規(guī)連接.
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.
有關(guān)示例代碼,請參見此處:http://wiki.python.org/moin/UdpCommunication一個>
See here for some example code: http://wiki.python.org/moin/UdpCommunication
這篇關(guān)于如何使 LAN 客戶端可以發(fā)現(xiàn)服務(wù)器的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網(wǎng)!