首页 > 解决方案 > 在 Python 中连接到本地服务器时遇到问题

问题描述

我目前正在关注如何使用 python 制作多人游戏的本教程:https ://www.youtube.com/watch?v=McoDjOCb2Zo

我目前正在尝试使用网络文件连接到服务器文件。运行服务器文件会打印出正确的信息,但是一旦我尝试使用网络文件连接到它,什么也没有发生。

这是我的服务器代码。当它运行时,它会打印出“等待连接,服务器已启动(我已经删除了我的 IP 地址,但我知道当我运行我的代码时我有正确的地址)

import socket
from _thread import *

server = "***.***.*.**"
port = 5555

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("Waitng for a connection, Server Started")

def threaded_client(conn):
    conn.send(str.encode("Connected"))
    reply = ""
    
    while True:
        try:
            data = conn.recieve(2048)
            reply = data.decode("utf-8")

            if not data:
                print("Disconnected")
                break
            else:
                print("Received", reply)
                print("Sending: ", reply)
            
            conn.sendall(str.encode(reply))
        except:
            break
    print("Lost Connection")
    conn.close()


while True:
    conn, addr = s.accept()
    print("Conneced to: ", addr)

    start_new_thread(threaded_client, (conn,))

这是我的网络的代码

import socket

class Network:
    def __init__(self):
        self.client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        self.server = "***.***.*.**"
        self.port = 5555
        self.addr = (self.server, self.port)
        self.id = self.connect()
        print(self.id)

    def connect(self):
        try:
            self.client.connect(self.addr)
            return self.client.recv(2048).decode()
        except:
            pass

n = Network()

当我在初始化服务器后运行此代码时,它应该打印出“已连接”

标签: python

解决方案


推荐阅读