socket通訊類比http服務之python版

來源:互聯網
上載者:User

直接見代碼,用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請求的方式。

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.