Python OSError: [Errno 107] 传输端点未连接

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/34249188/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 14:41:43  来源:igfitidea点击:

OSError: [Errno 107] Transport endpoint is not connected

pythonsockets

提问by daltonfury42

I am trying to learn how to use sockets in python to communicate between two computers. Unfortunately I get this error when everything seem to be right:

我正在尝试学习如何在 python 中使用套接字在两台计算机之间进行通信。不幸的是,当一切似乎都正确时,我收到此错误:

OSError: [Errno 107] Transport endpoint is not connected

OSError: [Errno 107] 传输端点未连接

Upon googling, I found that this is because the connection may have dropped. But I run both the client and server side of the program in the same machine itself. I tried connecting again from the client end and I get this:

谷歌搜索后,我发现这是因为连接可能已断开。但是我在同一台机器上同时运行程序的客户端和服务器端。我尝试从客户端再次连接,我得到了这个:

OSError: [Errno 106] Transport endpoint is already connected

OSError: [Errno 106] 传输端点已连接

indicating that the previous connection is still intact. I am pretty confused as to what is happening and how to make it work. Here is a screenscreen shot which shows what I am trying to do and the problem:

表明之前的连接仍然完好无损。我对正在发生的事情以及如何使其发挥作用感到非常困惑。这是一个屏幕截图,显示了我正在尝试做的事情和问题:

enter image description here

在此处输入图片说明

采纳答案by Iman Mirzadeh

I tested your code with a little change on python 3.5.0 and it works: I think the trick is in sock.accept()method which returns a tuple:

我在 python 3.5.0 上做了一点改动测试了你的代码,它有效:我认为诀窍在于sock.accept()返回一个元组的方法:

socket.accept()Accept a connection. The socket must be bound to an address and listening for connections. The return value is a pair(conn, address) where conn is a new socket object usable to send and receive data on the connection, and address is the address bound to the socket on the other end of the connection.

socket.accept()接受一个连接。套接字必须绑定到一个地址并侦听连接。该返回值是一个对(康涅狄格州,地址),其中conn是一个新的套接字对象可用于在连接上发送和接收数据,和地址是绑定到插座上的连接的另一端的地址。

server

服务器

#server
>>> import socket
>>> sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
>>> sock.bind(("localhost", 8081))
>>> sock.listen(2)
>>> conn, addr = sock.accept()
>>> data= conn.recv(1024).decode("ascii") 

client:

客户:

#client
>>> import socket
>>> sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
>>> sock.connect(("localhost",8081))
>>> sock.send("hi".encode())
2
>>> sock.send("hiiiiiii".encode())
8
>>> sock.send(("#"*1020).encode())
1020