[英]Searching for Socket hosts and displaying their IP Addresses Python
I'm creating a local client-server game on Python using sockets where a server is hosted on the local network and the clients on the network can connect to the server if they have the server's IP address.我正在使用套接字在 Python 上创建本地客户端 - 服务器游戏,其中服务器托管在本地网络上,如果网络上的客户端具有服务器的 IP 地址,则它们可以连接到服务器。 It's not a dedicated server so it just runs on another thread on a client's computer.
它不是专用服务器,因此它只是在客户端计算机上的另一个线程上运行。 Currently, the client has to manually enter the IP address of the server to connect to it.
目前,客户端必须手动输入服务器的 IP 地址才能连接到它。 I want the client to be able to search the network for avaialble servers join, but i'm not sure how to get the server to broadcast it's availability.
我希望客户端能够在网络中搜索可用的服务器加入,但我不确定如何让服务器广播它的可用性。
This is the server-side script:这是服务器端脚本:
totalConnections = 0
port = 5555
host=socket.gethostname()
IP = socket.gethostbyname(host) #this just fetches the computer's IP address so the server can use it
server = IP
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
try:
s.bind((server, port))
except socket.error as e:
str(e)
s.listen(2)
print("Waiting for a connection, Server Started")
while True:
conn, addr = s.accept()
print("Connected to:", addr)
totalConnections += 1
start_new_thread(threaded_client, (conn, currentPlayer))
currentPlayer += 1
def threaded_client(conn, player):
conn.send(pickle.dumps(all_data[player])) # sends player data to client
While True:
conn.sendall(pickle.dumps(reply))
This is the client-side:这是客户端:
class Network:
def __init__(self,ip):
self.client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self.server = ip
self.port = 5555
self.addr = (self.server, self.port)
self.p = self.connect()
def getP(self):
return self.p
def connect(self):
try:
self.client.connect(self.addr)
return pickle.loads(self.client.recv(2048*3))
except:
pass
def send(self, data):
try:
self.client.send(pickle.dumps(data))
return pickle.loads(self.client.recv(2048*3))
except socket.error as e:
print(e)
我找到了在特定 UDP 端口上使用多播的解决方案,所有客户端都连接到该端口,以便在它们之间共享数据: https : //pymotw.com/2/socket/multicast.html
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.