直接見代碼,用python編寫一個基於socket的c/S結構程式,然後雙方簡單類比http協議通訊,也可以直接通過瀏覽器來訪問伺服器。
伺服器端:#!/usr/bin/env python #encoding: utf-8import socket, sys, threading SERVER = '127.0.0.1' #主機IP PORT = 8080 #連接埠號碼 MAXTHREADS = 10RECVBUFLEN = 1024HTTPTAG = 'HTTP/1.'MYTAG = '^MyP 1.0'RSTR = ''''HTTP/1.1 200 OKProxy-Connection: Keep-AliveConnection: Keep-AliveContent-Length: 8296Via: 1.1 JA-ISA02Expires: Fri, 18 May 2012 09:05:56 GMTDate: Fri, 18 May 2012 09:05:56 GMTContent-Type: text/html;charset=gb2312Server: BWS/1.0Cache-Control: privatetest'''RSTR2 = '''my defined p... '''RSTR3 = '''unknown p... '''userlist = ['user01', 'user02']BADUSER = 'bad'class Checker(threading.Thread): def __init__(self,socket,num): threading.Thread.__init__(self) self.socket = socket self.num = num print 'thread started!' def run(self): while True: self.socket.listen(2) cs,address = self.socket.accept() recvstr = cs.recv(RECVBUFLEN) print '>>>>>>>>>>>>thread [%d] received:\r\n%s' % (self.num,recvstr) if recvstr == '': print 'empty request' cs.close() return TAG = recvstr.split('\r\n', 1)[0] if HTTPTAG in TAG: print 'HTTP Request' cs.send(RSTR) print 'response is: \r\n%s' % RSTR elif MYTAG in TAG: print 'My define Request' cs.send(RSTR2) print 'response is: \r\n%s' % RSTR2 else: print 'other request' cs.send(RSTR3) print 'response is: \r\n%s' % RSTR3 print '>>>>>>>>>>>>thread [%d] end check>>>>>>>>>>>>' % (self.num,) cs.close()class authServer(object): def __init__(self): self.socket = None def run(self): self.socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self.socket.bind((SERVER,PORT)) i = 0 chkerlist = [] while i<MAXTHREADS: chker = Checker(self.socket,i) chker.start() i = i + 1 chkerlist.append(chker) for chker in chkerlist: chker.join()if __name__ == '__main__': asvr = authServer() asvr.run() print 'ending'
用戶端:
#!/usr/bin/env python #encoding: utf-8import socket, threading SERVER = '127.0.0.1' #主機IP PORT = 8080 #連接埠號碼START = '^MyP 1.0' START2 = '^MyP 1.0' START3 = '[^st]' BUFLEN = 1024 USER_list = ['user01', 'user02']class connector(threading.Thread): def __init__(self,num): threading.Thread.__init__(self) self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self.num = num def run(self): try: self.sock.connect((SERVER,PORT)) self.sock.send(START) print '>>>>>sent ',START rstr = self.sock.recv(BUFLEN) print 'received>>>>>>>',rstr self.sock.close() return except socket.error,e: print e returnif __name__ == '__main__': cnlist = [] i = 0 while i<10: cn = connector(i) cn.start() cnlist.append(cn) i = i + 1 for cn in cnlist: cn.join()
伺服器端對請求的內容進行簡單分析,符合http格式的就提示為http請求並返回http格式的字串,所有線程都是短串連,一應一答即結束,可以說是類比了http請求的方式。