0

我正在同一代码中结合使用 Socket 编程和 pexpect。我已经让它工作了,但有一个小故障。选择 API 在第一次迭代中等待指定的 5 秒。一旦它收到来自客户端的输入,它就不再等待 5 秒,即使它是在循环中指定的。简而言之,在第一次客户端服务器交互发生后,select 没有任何效果!我了解如何在 C++ 中绕过它,但我对 Python 比较陌生,无法找出原因。我附上了下面的代码,是一个非常简单的代码。

#!/usr/bin/python
#Basic Functionailty: to create a process and to take inputs from client machines
#This input will be given to a background process which will display the user the parsed output
#using pexpect
import pexpect
import socket
import select

TCP_IP = '127.0.0.1'
TCP_PORT = 50050
BUFFER_SIZE = 1024

#spawning a pexpect process and printing everything before the prompt appears
child = pexpect.spawn('./pox.py')
child.expect ('POX>')
print child.before

#binding to a port number and acting as a server
server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server.bind((TCP_IP, TCP_PORT))
server.listen(1)
input = [server]

#loop infinitely and get input and serve it to the process
#in addition to which if the process shows some messages display
#it to the user
while 1:
  print 'Before select'
  inputready,outputready,exceptready = select.select(input,[],[],5)
  for s in inputready:
    if s == server:
      #if the input is from the server
      conn, addr = s.accept()
      print 'Connection address:', addr
      input.append(conn)
      data = conn.recv(BUFFER_SIZE)
      if not data: continue
      print "received data:", data
      child.sendline (data)

    else:
      #if a time out occurs check the pexpect if it has any debug messages
      i = child.expect ([pexpect.TIMEOUT, 'POX>'], timeout=1)
      print child.before
      if i == 0:
        print child.before
4

1 回答 1

1

您已修改input

input.append(conn)

(然后调用conn.recv以获取一些数据,这将阻塞直到有一些数据或 EOF,但大概有一些并且你得到了它)。

完成此操作后,在循环的下一次行程中,很可能有接收数据或 EOF 准备好在conn. 我假设您立即致电child.expect(因为s == conn,因此s != server)。我敢打赌,在这一点上,conn是在 EOF,所以它立即返回,什么也没做。 conn仍处于打开状态,并且仍在 中input,因此每次您调用select它时都会立即返回,告诉您可以从conn.

于 2013-09-10T07:32:15.677 回答