当前位置: 首页 > 知识库问答 >
问题:

Python套接字模块错误:WinError 10057

顾俊誉
2023-03-14

我正在尝试制作一个在线Python游戏,目前正在处理服务器文件和网络类(负责将服务器连接到客户端)。一切正常,但我一直在尝试将网络文件中的内容发送回服务器,但它不起作用。

我尝试将其放入try/except循环,并让它打印错误。现在,控制台打印出这个。

None
[WinError 10057] A request to send or receive data was disallowed because the socket is not connected and (when sending on a datagram socket using a sendto call) no address was supplied
A fine day to you my friend!
None

Process finished with exit code 0

客户端文件:

import socket

IPV4 = socket.AF_INET
TCP = socket.SOCK_STREAM
SERVER = "192.168.1.77" # Replace with the ip address of the server
PORT = 5555
BITS = 2048

class Network:
    def __init__(self):
        self.client = socket.socket(IPV4, TCP)
        self.server = SERVER
        self.port = PORT
        self.address = (SERVER, PORT)
        self.id = self.connect()
        print(self.id)

        # So the idea is that when we decode the message on line 30 (rewrite this later), it will give us the string
        # "Connected" to self.id, as it calls the function self.connect, which returns the message.

        # self.id # This would be so that we could give an id to each player, and send specific things to each player

    def connect(self):
        try:
            self.client.connect(self.address) # Connects our client to the server on the specified port
            return self.client.recv(BITS).decode()
            # Ideally when we connect we should send some form of validation token
        except:
            pass

    def send(self, data):
        try: # I think the problem is here!!!!
            self.client.send(str.encode(data))
            return self.client.recv(BITS).decode()
        except socket.error as e:
            print(e)
            print("A fine day to you my friend!")
n = Network()
print(n.send("hello"))
# print(n.send("working"))

如果我没有弄错的话,发送函数会出现问题。我收到的错误是由于我试图编码并发送数据(self.client.send(str.encode(data))。然后它会给我上面的错误消息。

服务器代码为:

import socket
from _thread import *
import sys

SERVER = "192.168.1.77" # (For now) the private ipv4 address of my computer (localhost)
PORT = 5555
MAX_PLAYERS = 2
BITS = 2048
IPV4 = socket.AF_INET
TCP = socket.SOCK_STREAM

# Setting up the socket
s = socket.socket(IPV4, TCP) # The arguments are the address family and socket type.
# AF_INET is the address family for Ipv4, and SOCK_STREAM is the socket type for TCP connections


try: # There is a chance that the port may be being used for something, or some other error may occur. If so, we want to find out what
    s.bind((SERVER, PORT))
except socket.error as e: # This will
    str(e)

s.listen(MAX_PLAYERS) # Opens up the port for connections
print("Waiting for a connection, Server Started")


def threaded_client(connection):
    connection.send(str.encode("Connected")) # Sends an encrypted message to the client
    reply = ""
    while True:
        try:
            data = connection.recv(BITS)
            reply = data.decode("utf-8") # Decodes the encrypted data

            if not data: # If we try to get some info from the client and we don't, we're going to disconnect
                print("Disconnected")
                break # and break out of the try loop
            else:
                print("Received: {}".format(reply))
                print("Sending: {}".format(reply))

            connection.sendall(str.encode(reply)) # Sends our encrypted reply
        except:
            break
            # Add possible errors when they occur

    print("Lost connection")
    connection.close()

while True:
    connection, address = s.accept() # Accepts incoming connections and stores the connection and address
    # Note: the connection is an object and the address is an ip address
    print("Connected to {}".format(address))
    start_new_thread(threaded_client, connection)

理想情况下,结果(假设我启动了服务器文件,并且它运行时没有任何错误)如下:

Connected
hello

为了进一步解释...我得到“连接”的原因是因为在连接方法中,我从服务器接收到一条加密的消息,我解码后返回self.id.self.id然后打印出来,这样就表明它连接到了服务器。

共有1个答案

岳杜吟
2023-03-14

服务器也会出错,这是问题的原因:

Waiting for a connection, Server Started
Connected to ('127.0.0.1', 1930)
Traceback (most recent call last):
  File "C:\server.py", line 54, in <module>
    start_new_thread(threaded_client, connection)
TypeError: 2nd arg must be a tuple

请改用以下方法:

start_new_thread(threaded_client, (connection,))

请注意,TCP是一种流协议,没有消息边界的概念,因此如果您不在流中设计协议来确定消息的开始和结束位置,那么最终会遇到一次发送多条消息的问题。

 类似资料:
  • 我试图编写套接字错误处理(确切地说是错误111-连接拒绝),但什么也没有发生。终端打印错误号111发生,但它没有做任何事情: Traceback(最近的调用为last):文件“test.py”,第20行,在s.connect((IP,PORT))中文件“/usr/lib/python2.7/socket.py”,第224行,在meth返回getattr(self._sock,name)(*args

  • 问题内容: 我正在尝试做的事情: 我现在正在尝试构建一个测试应用程序,只需在Android手机(4.2.2)(作为客户端)上的应用程序与在PC上运行的Java应用程序(Windows8)(作为服务器)通过套接字连接。 我已经完成的工作: 我已经在PC上的Java中为客户端和服务器编写了程序,并对其进行了积极的测试(建立了Connection)。 网络: 我的手机和PC都连接到我家里的wifi。PC

  • 问题内容: 我正在尝试为python中的类编写单元测试。该类在 init 上打开一个tcp套接字。我试图对此进行模拟,以便可以断言使用正确的值调用了连接,但是显然在单元测试中实际上并未发生。我已经厌倦了MagicMock,补丁程序等,但是还没有找到解决方案。 到目前为止我的班级看起来像 问题答案: 如果您只想断言被正确调用,这很简单 如果必须先导入模块才能访问,则需要稍微调整补丁:

  • 我试图使用任何NodeJS或NPM命令,但我总是得到以下错误: 套接字:(10106)无法加载或初始化请求的服务提供程序。 我正在运行Windows 10,我尝试再次重新安装nodejs,但仍然没有改变。

  • 我是Python新手,我想在我的应用程序中导入tweepy。我运行此代码(取自Tweepy官方文档): 它返回此错误: 回溯(最近一次调用):文件“C:/Users/user/PycharmProjects/TwitterPythonAnalytics/file3.py”,第1行,在导入tweepy文件“C:\Users\user\PycharmProjects\TwitterPythonAnal

  • 问题内容: 我一直在使用python dns模块。我试图在新的Linux安装上使用它,但该模块未加载。我试图清理并安装,但安装似乎无法正常进行。 更新了python版本和pip版本命令的输出 非常感谢你的帮助。 注意:-我在新计算机上安装了防火墙。我不确定它是否会影响导入。但我试图禁用它,但它似乎仍然无法正常工作。 问题答案: 我遇到了与dnspython相同的问题。 我的解决方案是从他们的官方G