[cpp]
/*
簡單的http服務器,參考《深入理解計算機系統》
*/
import "rsock.h"
import "rfile.h"
import "rdir.h"
main
{
rsock svr
rsock client
svr.listen 80
for svr.accept client
{
rstr s
s.m_buf.alloc 65536
s.m_buf.m_count=client.recv s.count,s.begin
proc client,s
client.close
}
}
class http_item
{
rstr name
rstr cont
}
proc(rsock& client,rstr& s)
{
s.print
vstr=s.split('\r\n')
rbuf<http_item> vitem
for i in vstr
{
pos=vstr[i].find ' '
http_item item
item.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')
return
path=v[0].cont.sub(0,v[0].cont.find(' '))
path='.'+path
rfile file(path)
ifn(file.read_all)
return
s='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_str
client.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'
else
return 'text/plain'
}