所以最近我一直在尝试使用Python进行多人游戏。我想到的游戏是《矮人要塞》,但有两个玩家而不是AI。为此,我一直在看很多教程,但是都没有帮助。我发现我刚刚复制并粘贴了代码以供以后编辑。这是非常糟糕的代码,但是我计划在我能使它正常工作时使其看起来更好。该程序本身可以正常运行,但是当我使用命令“ ngrok.exe tcp 1234”使用Ngrok托管端口,并让我和我的朋友使用不同的wi-fi尝试聊天室时,它将使客户端崩溃。请帮忙。我知道这并不是正在发生的最好的解释,但是请问任何可能需要帮助我的问题,我会回答他们。
#SERVER
#Import
from time import *
from socket import *
#Tell The User That They Are Setting Up The Server
print('Setup Server...')
sleep(1)
#Set Socket Stuff
s = socket(AF_INET,SOCK_STREAM)
hostName = gethostname()
IP = gethostbyname(hostName)
port = int(input("What is the port: "))
#Set Up Server
s.bind((hostName,port))
#Ask User To Put In Username
name = input("Enter Username: ")
#Tries To Locate Client
s.listen(1)
print('Waiting for incoming connections...')
#Accepts Client If It Gets It
connection,addr = s.accept()
print("Received connection from ",addr[0], "(",addr[1],")\n")
print('Connection Established. Connected From: {}, ({})'.format(addr[0],addr[0]))
#Gets The Connection From Client Side
clientName = connection.recv(1024)
clientName = clientName.decode()
print(clientName + ' has connected.')
print('Press [bye] to leave the chat room')
connection.send(name.encode())
#Game Loop
while True:
message = input('Me > ')
if message == '[bye]':
message = 'Good Night...'
connection.send(message.encode())
print("\n")
break
connection.send(message.encode())
message = connection.recv(1024)
message = message.decode()
print(clientName, '>', message)
#CLIENT
import time, socket, sys
print('Client Server...')
time.sleep(1)
#Get the hostname, IP Address from socket and set Port
soc = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
shost = socket.gethostname()
ip = socket.gethostbyname(shost)
port = int(input("Put port here: "))
#get information to connect with the server
print(shost, '({})'.format(ip))
server_host = input('Enter server\'s IP address:')
name = input('Enter Client\'s name: ')
#port = 1234
print('Trying to connect to the server: {}, ({})'.format(server_host, port))
time.sleep(1)
soc.connect((server_host, port))
print("Connected...\n")
soc.send(name.encode())
server_name = soc.recv(1024)
server_name = server_name.decode()
print('{} has joined...'.format(server_name))
print('Enter [bye] to exit.')
while True:
message = soc.recv(1024)
message = message.decode()
print(server_name, ">", message)
message = input(str("Me > "))
if message == "[bye]":
message = "Leaving the Chat room"
soc.send(message.encode())
print("\n")
break
soc.send(message.encode())