【问题标题】:An established connection was aborted by the software in your host machine - Python socket已建立的连接被主机中的软件中止 - Python 套接字
【发布时间】:2021-05-09 00:42:23
【问题描述】:

我正在尝试为我正在制作的游戏创建在线代码。显然,运行此代码会出错。错误是 [WinError 10053] 已建立的连接已被主机中的软件中止。

这是我的代码: 服务器

from _thread import *
import sys

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

host = socket.gethostname()
server = 'localhost'
port = 5555

server_ip = socket.gethostbyname(server)

try:
    s.bind((server, port))
except socket.error as e:
    print(str(e))

s.listen(2)
print("Currently waiting for other users...")

currentId = "0"
pos = ["0:50,50", "1:100,100"]
def threaded_client(conn):
    global currentId, pos
    conn.send(str.encode(currentId))
    currentId = "1"
    reply = ''
    while True:
        try:
            data = conn.recv(2048)
            reply = data.decode('utf-8')
            if not data:
                conn.send(str.encode("Goodbye"))
                break
            else:
                print("Recieved: " + reply)
                arr = reply.split(":")
                id = int(arr[0])
                pos[id] = reply

                if id == 0: nid = 1
                if id == 1: nid = 0

                reply = pos[nid][:]
                print("Sending: " + reply)

            conn.sendall(str.encode(reply))
        except:
            break

    print("Connection Closed")
    conn.close()

while True:
    conn, addr = s.accept()

    start_new_thread(threaded_client, (conn,))

客户

import time

class Network:
    def __init__(self):
        randomvar = "."
        while True:
            try:
                self.client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
                self.host = "localhost" # For this to work on your machine this must be equal to the ipv4 address of the machine running the server
                                            # You can find this address by typing ipconfig in CMD and copying the ipv4 address. Again this must be the servers
                                            # ipv4 address. This feild will be the same for all your clients.
                self.port = 5555
                self.addr = (self.host, self.port)
                self.id = self.connect()
                break
            except ConnectionRefusedError:

                if randomvar != "Waiting for server...":
                    print("Waiting for server...")
                    randomvar = "Waiting for server..."

    def getNumber(self):
        pass

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

    def send(self, data):
        """
        :param data: str
        :return: str
        """
        try:
            self.client.send(str.encode(data))
            reply = self.client.recv(2048).decode()
            return reply
        except socket.error as e:
            return str(e)

n = Network()
print(n.send("Host"))
print(n.send("hello"))

在服务器上,它接收的唯一内容是Host,而不是hello。这就是我得到错误的地方,但它不会告诉我它是哪一行。

有什么帮助吗?

【问题讨论】:

    标签: python sockets server


    【解决方案1】:

    您忽略了异常。相反,将其打印出来以了解问题所在:

    Traceback (most recent call last):
      File "D:\temp\python\server.py", line 39, in threaded_client
        id = int(arr[0])
    ValueError: invalid literal for int() with base 10: 'Host'
    

    这导致这一行:

    id = int(arr[0])
    

    看起来服务器期望消息采用id:msg 的形式,但客户端没有发送该消息。它只是发送没有 id 的消息。您可以在服务器中检查。

    arr = reply.split(":")
    if len(arr) != 2 or !arr[0].isdigit():
        # Handle error....
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-02-29
      • 2012-12-27
      • 2022-01-15
      相关资源
      最近更新 更多