[Cpp]
/*
For a simple http server, refer to in-depth understanding of computer systems
*/
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 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 {
If (v. empty | v. get (0). name! = 'Get ')
Return
Path = v [0]. cont. sub (0, v [0]. cont. find (''))
Path = '.' + path
Rfile file (path)
Interferon (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'
}