tcp.py
上传用户:quxuerui
上传日期:2018-01-08
资源大小:41811k
文件大小:5k
源码类别:

网格计算

开发平台:

Java

  1. #Licensed to the Apache Software Foundation (ASF) under one
  2. #or more contributor license agreements.  See the NOTICE file
  3. #distributed with this work for additional information
  4. #regarding copyright ownership.  The ASF licenses this file
  5. #to you under the Apache License, Version 2.0 (the
  6. #"License"); you may not use this file except in compliance
  7. #with the License.  You may obtain a copy of the License at
  8. #     http://www.apache.org/licenses/LICENSE-2.0
  9. #Unless required by applicable law or agreed to in writing, software
  10. #distributed under the License is distributed on an "AS IS" BASIS,
  11. #WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. #See the License for the specific language governing permissions and
  13. #limitations under the License.
  14. # $Id:tcp.py 6172 2007-05-22 20:26:54Z zim $
  15. #
  16. #------------------------------------------------------------------------------
  17. """ TCP related classes. """
  18. import socket, re, string
  19. reAddress    = re.compile(":")
  20. reMayBeIp = re.compile("^d+.d+.d+.d+$")
  21. reValidPort = re.compile("^d+$")
  22. class Error(Exception):
  23.     def __init__(self, msg=''):
  24.         self.message = msg
  25.         Exception.__init__(self, msg)
  26.     def __repr__(self):
  27.         return self.message
  28. class tcpError(Error):
  29.     def __init__(self, message):
  30.         Error.__init__(self, message)
  31. class tcpSocket:
  32.     def __init__(self, address, timeout=30, autoflush=0):
  33.         """Constructs a tcpSocket object.
  34.            address - standard tcp address (HOST:PORT)
  35.            timeout - socket timeout"""
  36.         self.address = address
  37.         self.__autoFlush = autoflush
  38.         self.__remoteSock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
  39.         self.__remoteSock.settimeout(timeout)
  40.         self.host = None
  41.         self.port = None
  42.         splitAddress = address
  43.         if isinstance(address, (tuple, list)):
  44.             self.host = address[0]
  45.             self.port = int(address[1])
  46.         else:
  47.             splitAddress = get_address_tuple(address)
  48.             if not splitAddress[0]:
  49.                 self.host = 'localhost'
  50.             else:
  51.                 self.host = splitAddress[0]
  52.             self.port = int(splitAddress[1])
  53.         self.__fileObjectOut = ''
  54.         self.__fileObjectIn = ''
  55.     def __repr__(self):
  56.         return self.address
  57.     def __iter__(self):
  58.         return self
  59.     def next(self):
  60.         sockLine = self.read()
  61.         if not sockLine:
  62.             raise StopIteration
  63.         return sockLine
  64.     def open(self):
  65.         """Attempts to open a socket to the specified address."""
  66.         socketAddress = (self.host, self.port)
  67.         try:
  68.             self.__remoteSock.connect(socketAddress)
  69.             if self.__autoFlush:
  70.                 self.__fileObjectOut = self.__remoteSock.makefile('wb', 0)
  71.             else:
  72.                 self.__fileObjectOut = self.__remoteSock.makefile('wb')
  73.             self.__fileObjectIn  = self.__remoteSock.makefile('rb', 0)
  74.         except:
  75.             raise tcpError, "connection failure: %s" % self.address
  76.     def flush(self):
  77.         """Flushes write buffer."""
  78.         self.__fileObjectOut.flush()
  79.     def close(self):
  80.         """Attempts to close and open socket connection"""
  81.         try:
  82.             self.__remoteSock.close()
  83.             self.__fileObjectOut.close()
  84.             self.__fileObjectIn.close()
  85.         except socket.error, exceptionObject:
  86.             exceptionMessage = "close failure %s %s" % (self.address,
  87.                 exceptionObject.__str__())
  88.             raise tcpError, exceptionMessage
  89.     def verify(self):
  90.         """Verifies that a given IP address/host and port are valid. This
  91.            method will not attempt to open a socket to the specified address.
  92.         """
  93.         isValidAddress = False
  94.         if reMayBeIp.match(self.host):
  95.             if check_ip_address(self.host):
  96.                 if reValidPort.match(str(self.port)):
  97.                     isValidAddress = True
  98.         else:
  99.             if reValidPort.match(str(self.port)):
  100.                 isValidAddress = True
  101.         return(isValidAddress)
  102.     def read(self):
  103.         """Reads a line off of the active socket."""
  104.         return self.__fileObjectIn.readline()
  105.     def write(self, string):
  106.         """Writes a string to the active socket."""
  107.         print >> self.__fileObjectOut, string
  108. def check_net_address(address):
  109.     valid = True
  110.     pieces = string.split(address, '.')
  111.     if len(pieces) != 4:
  112.         valid = False
  113.     else:
  114.         for piece in pieces:
  115.             if int(piece) < 0 or int(piece) > 255:
  116.                 valid = False
  117.     return valid
  118. def check_ip_address(address):
  119.     valid = True
  120.     pieces = string.split(address, '.')
  121.     if len(pieces) != 4:
  122.         valid = False
  123.     else:
  124.         if int(pieces[0]) < 1 or int(pieces[0]) > 254:
  125.             valid = False
  126.         for i in range(1,4):
  127.             if int(pieces[i]) < 0 or int(pieces[i]) > 255:
  128.                 valid = False
  129.     return valid
  130. def get_address_tuple(address):
  131.     """ Returns an address tuple for TCP address.
  132.         address - TCP address of the form host:port
  133.         returns address tuple (host, port)
  134.     """
  135.     addressList = reAddress.split(address)
  136.     addressTuple = (addressList[0], int(addressList[1]))
  137.     return addressTuple