Python 连接套接字进行处理

Python connect socket to process

我有一个(非常)简单的网络服务器,我用 C 写的,我想测试它。我写它是为了让它在 stdin 上获取数据并在 stdout 上发送。我如何将套接字(使用 socket.accept() 创建)的 input/output 连接到使用 subprocess.Popen 创建的进程的 input/output?

听起来很简单,对吧?这是杀手:我是 运行 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".

我遇到了同样的问题,并尝试以同样的方式绑定套接字,也在 windows 上。我提出的解决方案是共享套接字并将其绑定到 stdinstdout 的进程。我的解决方案完全在 python 中,但我想它们很容易转换。

import socket, subprocess

sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.bind(('', PORT))
sock.listen(5)
cli, addr = sock.accept()

process = subprocess.Popen([PROG], stdin=subprocess.PIPE)
process.stdin.write(cli.share(process.pid))
process.stdin.flush()

# you can now use `cli` as client normally

而在另一个进程中:

import sys, os, socket

sock = socket.fromshare(os.read(sys.stdin.fileno(), 372))
sys.stdin = sock.makefile("r")
sys.stdout = sock.makefile("w")

# stdin and stdout now write to `sock`

372 是测量的 socket.share 调用的 len。我不知道这是否是恒定的,但它对我有用。这仅在 windows 中可用,因为 share 功能仅在 OS.

中可用