[英]Connection refused with python sockets
So I am trying to make a server program that will call the client program. 因此,我正在尝试制作一个将调用客户端程序的服务器程序。 The server client work fine if I call them myself from the command line but the connection is refused when the server calls it.
如果我自己从命令行调用服务器客户端,则服务器客户端可以正常工作,但是服务器调用时连接被拒绝。 Why is this not working?
为什么这不起作用?
This is the server code: 这是服务器代码:
import socket,os
s = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
try:
os.remove("/tmp/SocketTest")
except OSError:
pass
s.bind("/tmp/SocketTest")
os.system("python compute.py")#compute is the client
#execfile('compute.py')
s.listen(1)
conn, addr = s.accept()
while 1:
data = conn.recv(1024)
if not data: break
conn.send(data)
conn.close()
This is the client code: 这是客户端代码:
import socket
s = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
s.connect("/tmp/SocketTest")
s.send('Hello, world \n')
s.send('its a mighty fine day')
data = s.recv(1024)
s.close()
print 'Received', repr(data)
os.system
will run the command you give it to completion, and you're doing this before you call listen
. os.system
将运行您提供给它的命令以完成操作,并且您在调用listen
之前正在执行此操作。 As such, the client will try to connect to the server before it's listening. 这样,客户端将在侦听之前尝试连接到服务器。 Only once the client exits will the server move on past that line of code to actually start listening and accepting connections.
只有客户端退出后,服务器才会越过该行代码以实际开始侦听和接受连接。
What you probably want to do is after the call to listen
, but before the call to accept
(which is when you start blocking), use subprocess.Popen
to spawn a subprocess and do not wait on it . 您可能想做的是在
listen
调用之后,但是在accept
调用之前(即开始阻塞时),使用subprocess.Popen
生成一个子进程, 而不要等待它 。
I think the error is that you're calling compute.py
before calling listen
. 我认为错误是你打电话
compute.py
调用之前listen
。
os.system
will block your server until the call to python compute.py
is completed. os.system
将阻塞您的服务器,直到对python compute.py
的调用完成为止。
Try subprocess.Popen to spawn the call to compute.py
in parallel to your server in a non blocking manner. 尝试subprocess.Popen产卵调用
compute.py
在平行于你的服务器在非阻塞的方式。 Calling subprocess.Popen
will launch python compute.py
in a new process, and will continue executing the next line conn, addr = s.accept()
) 调用
subprocess.Popen
将推出python compute.py
在一个新的进程,并将继续执行下一行conn, addr = s.accept()
#!/usr/bin/env python
import socket
import os
import subprocess
s = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
try:
os.remove("/tmp/SocketTest")
except OSError:
pass
s.bind("/tmp/SocketTest")
s.listen(1)
sp = subprocess.Popen(["/usr/bin/env", "python", "compute.py"])
conn, addr = s.accept()
while 1:
data = conn.recv(1024)
if not data:
break
conn.send(data)
conn.close()
That outputs: 输出:
Received 'Hello, world \nits a mighty fine day'
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.