我试图破解一种在两台计算机之间发送邮件的方法。以下代码创建用于接收消息的线程。
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()
我收到以下错误:
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
这是我的Scala发件人,它试图连接到Python部分并发送&#34; hello world&#34;一秒一次。
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()
答案 0 :(得分:0)
conn, addr = soc.accept() # Establish connection with client.
...
msg_binary=recv_one_message(soc)
您需要接收从accept(conn
)获得的连接套接字上的数据,而不是在侦听器套接字(soc
)上接收数据。