1.将TCP服务归类到一个类,用类的形式进行表示TCP服务
import socket
class TCPServer:
def __init__(self):
pass
def OpenServer(self,HOST='',PORT=7000):
try:
sock=socket.socket(socket.AF_INET,socket.SOCK_STREAM)
except socket.error:
print 'Server error:Unable to open socket'
sock.bind((HOST,PORT))
sock.listen(5)
return sock
def EstablishConnection(self,sock,connection_handler):
while 1:
client_socket,address=sock.accept()
print 'connection from','address'
thread.start_new_thread(connection_handler,(client_socket,))
def closeConnection(self,sock):
sock.close()
2.面向对象中的一个比较强的东西就是:设计模式
应用设计模式进行写类将这些类对象组织起来处理吧!
[先来分析一下Python中的抽象类实现方法吧!]
A.简单的实现方案如下:
- def abstract():
- raise NotImplementedError("abstract")
-
- class A:
- def __init__(self): abstract()
-
- class B(A):
- def __init__(self):
- print self.__class__.__name__
B.稍复杂但灵活的方法:
- def abstract():
- raise NotImplementedError("abstract")
-
- class A:
- def __init__(self):
- if self.__class__ is A: abstract()
- print "A"
-
- class B(A):
- def __init__(self):
- A.__init__(self)
- print "B"
来看具体的实现代码吧!
import socket,thread
class TCPConnection:
self.state=TCPClosed(self.sock)
def __init__(self,host,port):
self.host=host
self.port=port
self.sock=socket.socket(socket.AF_INET,socket.SOCK_STREAM)
self.sock.bind((host,port))
self.sock.listen(5)
self.state=TCPListen(self.sock)
def OpenConnection(self):
if state is TCPClosed:self.state=TCPListen
if state is TCPListen:
self.clisock=self.state.OpenConnection()
self.state=TCPEstablished(self.clisock)
def HandleConnection(self):
if state is TCPClosed:raise CloseStateError
if state is TCPListen:raise ListenStateError
if state is TCPEstablished:
self.state.HandleConnection(some_handler)
self.state=TCPListen(self.sock)
def CloseConnection():
self.state=TCPClose(self.sock)
self.state.CloseConnection()
#写一个抽象类然后让子类进行实现
class TCPState:
def __init__(self,sock):
self.sock=sock
def OpenConnection(self):
pass
def HandleConnection(self):
pass
def CloseConnection(self):
pass
class TCPClosed(TCPState):
def CloseConnection(self,sock):
sock.close()
class TCPListen(TCPState):
def OpenConnection(self,sock):
clisock,addr=sock.accept()
return clisock
class TCPEstablished(TCPState):
def HandleConnection(self,handler):
thread.start_new_thread(handler,(self.sock,))
阅读(981) | 评论(0) | 转发(0) |