【问题标题】:Searching for Socket hosts and displaying their IP Addresses Python搜索 Socket 主机并显示它们的 IP 地址 Python
【发布时间】:2020-05-14 19:57:35
【问题描述】:

我正在使用套接字在 Python 上创建本地客户端-服务器游戏,其中服务器托管在本地网络上,如果网络上的客户端具有服务器的 IP 地址,则可以连接到服务器。它不是专用服务器,因此它只是在客户端计算机上的另一个线程上运行。目前,客户端必须手动输入服务器的 IP 地址才能连接到它。我希望客户端能够在网络中搜索可用的服务器加入,但我不确定如何让服务器广播它的可用性。

这是服务器端脚本:

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

这是客户端:

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) 

【问题讨论】:

    标签: python-3.x sockets server


    【解决方案1】:

    我找到了在所有客户端都连接到的特定 UDP 端口上使用多播的解决方案,以便可以在它们之间共享数据:https://pymotw.com/2/socket/multicast.html

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-09-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-10-25
      • 2011-10-02
      • 2014-12-19
      • 2014-12-02
      相关资源
      最近更新 更多