OSError: [Errno 107] Transport endpoint is not connected

半世苍凉 提交于 2021-02-04 13:02:47

问题


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:

OSError: [Errno 107] Transport endpoint is not connected

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

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:


回答1:


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:

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.

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


来源:https://stackoverflow.com/questions/34249188/oserror-errno-107-transport-endpoint-is-not-connected

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!