关闭文件的I / O操作|管道输出到标准输出

时间:2019-02-23 14:56:33

标签: python sockets tcp

我正在编写一个小的python脚本,该脚本从ssl流(tcp套接字)读取/写入文本。

我想在退出时重新启动它,例如,如果连接崩溃,它将重新启动并监听新的连接。

重新启动时,它会显示以下错误:I/O operation on closed file。 我发现它在下面的这次通话中崩溃:set_nonblocking(get_io(io)[0].fileno())

我试图重置stdout / stdin,但没有解决。

有什么想法吗?

def main(args,queue):                                                
  try:
    io  = None
    server(lport, io = io)
  except Exception as e:
    queue.put(1)
    exit(1)
  queue.put(0)
  exit(0)


def server(port, udp = False, term = None, io = None):         
  """connect std{in,out} to TCP (or UDP) socket (server)"""

  set_nonblocking(get_io(io)[0].fileno())
  sock = create_socket()
  sock.setsockopt(S.SOL_SOCKET, S.SO_REUSEADDR, 1)
  KEYFILE = "server.key"
  CERTFILE = "server.crt"
  context = ssl.create_default_context(ssl.Purpose.CLIENT_AUTH)
  sock.bind(('', port))

  while True:
    try:
      sock.listen(1); clientsock, addr = sock.accept()
      connstream = ssl.wrap_socket(clientsock, server_side=True, certfile=CERTFILE, keyfile=KEYFILE)
    except:
      print("SSL-Handshake failed, retrying..")
      time.sleep(0.1)
      continue
    break

  print(connstream.read())
  handle_io(connstream, term = term, io = io)

def handle(conn):
  while True:
      data = conn.recv()
      if not data: break
      else: print(data)

def create_socket(udp = False):
  return S.socket(S.AF_INET, S.SOCK_DGRAM if udp else S.SOCK_STREAM)

def handle_io(sock, udp = False, addr = None, term = None, io = None):
  """
  handle I/O (connect std{in/out} to socket);
  terminates if term is passed and term.is_set()
  """
  i, o = get_io(io)
  try:
    while term is None or not term.is_set():
      sin = [sock,i] if (not udp or addr) and not i.closed else [sock]
      rs, _, _ = select.select(sin, [], [])
      if sock in rs:
        data = sock.recv(4096)
        if udp and not addr:
          addr = clientaddr; sock.connect(addr)
        if not data: return CLOSED_SOCK
        binwrite(o, data); o.flush()
      if i in rs:
        data = binread(i, 4096)
        if udp: sock.sendto(data, addr)
        else:   sock.sendall(data)
  finally:
    sock.close()

CLOSED_SOCK = "__CLOSED_SOCK__"

def get_io(io):
  return (sys.stdin, sys.stdout) if io is None else io

def set_nonblocking(fd):
  """make fd non-blocking."""
  flags = fcntl.fcntl(fd, fcntl.F_GETFL)
  flags = flags | os.O_NONBLOCK
  fcntl.fcntl(fd, fcntl.F_SETFL, flags)

args = None

if __name__ == "__main__":
  args = sys.argv[1:]

  while True:
    queue = Queue.Queue()
    try:
      thread = Thread(target = main, args =[args,queue])
      thread.daemon=True
      thread.start()
      while thread.isAlive(): thread.join(1)
    except KeyboardInterrupt: exit(2)
    time.sleep(5.0)
    print("[*] Relaunching Execution..")
  exitCode = queue.get() or 0
  exit(exitCode)

我的进口商品:

from __future__ import print_function
import os
import time
import httplib, urllib
from threading import Thread
import Queue
import argparse, fcntl, os, select, subprocess, sys
import socket as S
import ssl
from OpenSSL import SSL

0 个答案:

没有答案