我编写了一个非常简单的C语言Web服务器,我想测试它。我编写它以便从stdin获取数据并通过stdout发送出去。如何将socket(使用socket.accept()创建)的输入/输出连接到使用subprocess.Popen()创建的进程的输入/输出?
听起来很简单,对吧?但问题在于:我正在运行Windows。
有人能帮忙吗?
这是我尝试过的内容:
1. 将客户端对象本身作为stdin/out传递给subprocess.Popen。(尝试一下也无妨。) 2. 将socket.makefile()结果作为stdin/out传递给subprocess.Popen。 3. 将套接字的文件编号传递给os.fdopen()。
此外,为了避免问题不清楚,这里是我的代码精简版本:
听起来很简单,对吧?但问题在于:我正在运行Windows。
有人能帮忙吗?
这是我尝试过的内容:
1. 将客户端对象本身作为stdin/out传递给subprocess.Popen。(尝试一下也无妨。) 2. 将socket.makefile()结果作为stdin/out传递给subprocess.Popen。 3. 将套接字的文件编号传递给os.fdopen()。
此外,为了避免问题不清楚,这里是我的代码精简版本:
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.bind(('', PORT))
sock.listen(5)
cli, addr = sock.accept()
p = subprocess.Popen([PROG])
#I want to connect 'p' to the 'cli' socket so whatever it sends on stdout
#goes to the client and whatever the client sends goes to its stdin.
#I've tried:
p = subprocess.Popen([PROG], stdin = cli.makefile("r"), stdout = cli.makefile("w"))
p = subprocess.Popen([PROG], stdin = cli, stdout = cli)
p = subprocess.Popen([PROG], stdin = os.fdopen(cli.fileno(), "r"), stdout = os.fdopen(cli.fileno(), "w"))
#but all of them give me either "Bad file descriptor" or "The handle is invalid".
socket.share
函数(在Python中)。我认为你至少应该考虑这个解决方案。 - Rolando Urquiza