簡單的http伺服器源碼

來源:互聯網
上載者:User
/*簡單的http伺服器,參考《深入理解電腦系統》運行後在瀏覽器輸入http://127.0.0.1/1.htm*/import "rsock.h"import "rfile.h"import "rdir.h"main{rsock svrrsock clientsvr.listen 80for svr.accept client{rstr ss.m_buf.alloc 65536s.m_buf.m_count=client.recv s.count,s.beginproc client,sclient.close}}class http_item{rstr namerstr cont}proc(rsock& client,rstr& s){s.printvstr=s.split('\r\n')rbuf<http_item> vitemfor i in vstr{pos=vstr[i].find ' 'http_item itemitem.name=vstr[i].sub(0,pos)item.cont=vstr[i].sub(pos+1)vitem+=item}proc client,vitem}proc(rsock& client,rbuf<http_item>& v){if(v.empty||v.get(0).name!='GET')returnpath=v[0].cont.sub(0,v[0].cont.find(' '))path='.'+pathrfile file(path)ifn(file.read_all)returns='HTTP/1.1 200 OK\r\n's+='Server: R++ Web Server\r\n's+='Content-Length: '+rstr(file.size)+'\r\n's+='Content-type: '+get_type(path)+'\r\n\r\n's+=file.m_strclient.send(s.count,s.begin)}rstr get_type(rstr name){name=rdir.get_suffix(rdir.get_name(name))if(name=='htm'||name=='html')return 'text/html'elif(name=='gif')return 'image/gif'elif(name=='jpg')return 'image/jpg'elsereturn 'text/plain'}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.