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:
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
>>> 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
>>> 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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With