JuhoKupiainen JuhoKupiainen - 1 month ago 10
Python Question

Python socket: [Errno 107] Transport endpoint is not connected

I'm trying to hack together a way to send messages between two computers. The following code creates a thread for receiving messages.

import socket # Import socket module
import threading
import traceback
def recv_one_message(sock):
lengthbuf = recvall(sock, 4)
length, = struct.unpack('!I', lengthbuf)
return recvall(sock, length)

def recvall(sock, count):
buf = b''
while count:
newbuf = sock.recv(count)
if not newbuf: return None
buf += newbuf
count -= len(newbuf)
return buf

host="ec2-35-160-33-3.us-west-2.compute.amazonaws.com"
kill_threads=False

def receive_thread():
while not kill_threads:
try:
# Create a socket object
soc = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
soc.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
port = 8502 # Reserve a port for your service.
soc.bind((host, port)) # Bind to the port
print("port bound")
soc.settimeout(10)
soc.listen(50000000) # Now wait for client connection.
conn, addr = soc.accept() # Establish connection with client.
soc.settimeout(None)
print ("Got connection from",addr)
while not kill_threads:
msg_binary=recv_one_message(soc)
msg=str(msg_binary, "utf-8")
print(msg)
except Exception:
traceback.print_exc()
try:
conn.close()
soc.close()
except Exception:
traceback.print_exc()

t2 = threading.Thread(target=receive_thread)
t2.daemon=True
t2.start()


I get the following error:

Traceback (most recent call last):
File "<ipython-input-3-eaef71a53845>", line 59, in receive_thread
msg_binary=recv_one_message(soc)
File "<ipython-input-3-eaef71a53845>", line 7, in recv_one_message
lengthbuf = recvall(sock, 4)
File "<ipython-input-3-eaef71a53845>", line 14, in recvall
newbuf = sock.recv(count)
OSError: [Errno 107] Transport endpoint is not connected


Here is my Scala sender that tries to connect to the Python part and sends "hello world" once a second.

import java.io._
import java.net._
import java.nio.charset.Charset

val host = "ec2-35-160-33-3.us-west-2.compute.amazonaws.com"
new Thread {
override def run() {
while (true) {
try {
print("trying to establish connection")
val soc = new Socket(host, 8502)
val dout = new DataOutputStream(soc.getOutputStream())
print("connection established")
val serializedMessage = "hello world"
val serializedMessageBytes = (serializedMessage).getBytes(Charset.forName("UTF-8"))
while (true) {
dout.write(serializedMessageBytes.length)
dout.write(serializedMessageBytes)
dout.flush()
Thread.sleep(1000)
}
} catch {
case e => e.printStackTrace()
}
}
}
}.start()

Answer
        conn, addr = soc.accept()  # Establish connection with client.
        ...
            msg_binary=recv_one_message(soc)

You need to receive the data on the connected socket you got from accept (conn) and not on the listener socket (soc).