TCP Package

tcp/interfaces.fi

"""
TCP Interfaces
"""

class TCP_req(object):
  
  def connect(self,host,port):
    """
    @return: TCP_conn
    """
    raise NotImplementedError()
  
class TCP_ind(object):

  def new_connection(self,connection):
    raise NotImplementedError()
  
class TCP_conn_req(object):
  
  def send(self,data):
    raise NotImplementedError()

  def close(self):
    raise NotImplementedError()
    
class TCP_conn_ind(object):
  
  def recv(self,data):
    raise NotImplementedError()

  def close(self):
    raise NotImplementedError()

tcp/tcp_usage.py

'''
TCP usage objects.
'''

import logging
log = logging.getLogger(__name__)
import socket
import select
import threading
from tcp.interfaces import *

class TCP_conn(TCP_conn_req): # connection entity

  def __init__(self,tcp,):
    self._tcp = tcp
    self._ind = None
    self.socket = None
    self.buf_size = 1024

  def connect(self,host,port): # on connect
    ## create and connect
    self.socket = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
    self.socket.connect((host,port))

  def set_socket(self,socket): # on accept
    self.socket = socket

  def set_ind(self,ind):
    self._ind = ind

  def send(self,data):
    self.socket.send(data)
    
  def do_recv(self):
    data = self.socket.recv(self.buf_size)
    if data:
      self._ind.recv(data)
    else:
      self._ind.close()
    
  def close(self):
    self._tcp.remove_conn(self)
    self.socket.close()

class TCP(threading.Thread,TCP_req): # layer main manager entity

  def __init__(self):
    threading.Thread.__init__(self)
    self._ind = None
    self._connections = dict() # (socket,TCP_conn)
    self.server_socket = None
    self._do_shutdown = False
  
  def set_ind(self,ind):
    self._ind = ind
  
  def be_server(self,port):
    s = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
    s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
    s.bind(("",port))
    s.listen(5)
    log.debug("Listening connections at port " + str(port))
    self.server_socket = s
      
  def run(self):
    ## loop
    while not self._do_shutdown:
      ## init read list
      wait_reads = list()
      for conn in self._connections.values():
        wait_reads.append(conn.socket)
      if self.server_socket is not None:
        wait_reads.append(self.server_socket)
      ## Block and wait here
      #log.debug("waiting IO ..")
      wait_time = 3.0
      reads, writes, excepts = select.select(wait_reads,[],[],wait_time) 
      for s in reads:
        if s == self.server_socket:
          self.do_accept()
        else:
          self._connections[s].do_recv()
    ## clean up
    log.debug("tcp cleanup")
    if self.server_socket is not None:
      self.server_socket.close()
    for conn in self._connections:
      conn.close()
                
  def do_accept(self):
    s,addr = self.server_socket.accept()
    conn = TCP_conn(self)
    conn.set_socket(s)
    self._connections[conn.socket] = conn 
    self._ind.new_connection(conn)
                
  def shutdown(self):
    log.debug("tcp shutdown")
    self._do_shutdown = True
  
  def connect(self,host,port):
    conn = TCP_conn(self)
    conn.connect(host,port)
    self._connections[conn.socket] = conn 
    return conn

  def remove_conn(self,conn):
    del self._connections[conn.socket] 
 
__all__ = ("TCP_conn","TCP")
Last modified: 2013/07/01 14:42