我一直试图建立一个与朋友一起玩的游戏。我们都住在不同的地方,拥有不同的IP,WiFi等。我使用socket
使用SOCK_DGRAM
在我自己的计算机上开始编码。我在自己的计算机上运行服务器和客户端代码时工作正常,但当我的朋友试图运行客户端代码时,他们无法向我的服务器发送任何内容。没有抛出任何错误,他们发送的内容并没有被我的服务器接收。
这是服务器代码:
import socket
host = "192.168.88.191"
port = 2000
connections = Connections() # Where I store my friends' way of contacting the server
player_list = [] # A list of players to be used by my Players class
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s.bind((host, port))
s.setblocking(False)
print("Server started")
while True:
try:
data, addr = s.recvfrom(1024)
got_data = True
except OSError:
got_data = False
if got_data:
if not addr in connections.addresses:
connections.addresses.append(addr) # Store all new addresses
player_list.append(Players(len(player_list))) # Append to player list (don't worry about this part)
data = data.decode("utf-8")
print("Message from " + str(addr) + ": " + data)
player_list[int(addr[1] - 2001)].move(data, player_list) # Function for game logic
message = ""
for player in player_list:
message += str(player.number) + " " + str(player.x) + " " + str(player.y) + "," # Make the message that I want to send
message = message[:-1]
print("Sending: " + message)
for address in connections.addresses:
s.sendto(message.encode("utf-8"), address)
以下是客户端代码:
class Sock():
def __init__(self):
self.host = "192.168.88.191"
self.port = 2000
self.server = (self.host, 2000)
self.s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
while True:
try:
print("Trying to connect on port " + str(self.port))
self.s.bind((self.host, self.port))
except OSError:
self.port += 1
else:
self.s.setblocking(False)
print("Connected on port " + str(self.port) + "!")
break
def send_data(self, message):
print("Sending: " + message)
self.s.sendto(message.encode("utf-8"), self.server)
def recieve_data(self):
try:
data, addr = self.s.recvfrom(1024)
data = data.decode("utf-8")
print("Recieved from server: " + data)
return data
except socket.error:
pass
我的IP是192.168.88.191。我会假设我的朋友需要在客户端代码中使用他们的IP,但在哪里?我知道您可以通过socket.gethostbyname(socket.gethostname())
self.server = (self.host, 2000)
替换了self.server = (socket.gethostbyname(socket.gethostname()), 2000)
,尽管正如我所说,我不知道这是否真的是我们所做的。