How do I write a web server in C/C++ on linux [closed]

末鹿安然 提交于 2019-12-02 14:10:31

From top-down, you'll need to know about:

  • HTTP Protocol
  • TCP server - BSD socket programming
  • writing a basic Unix daemon (persistent service)
  • process management (fork)
  • parsing text (read a configuration text file)
  • file handling (I/O)
  • debugging C / C++ programming :)

So you will have to learn about writing a basic Unix application, BSD socket programming for the TCP/IP network programming, and the HTTP protocol.

Commonly used texts include:

Unix application development:

  • Advanced Programming in the Unix Environment, Stevens & Rago
  • Advanced Unix Programming

TCP/IP (sockets) programming:

  • Unix Network Programming, Volume 1 Stevens et all
  • TCP/IP Illustrated, Stevens
  • Ineternetworking with TCP/IP, Volume 3, Comer

HTTP Protocol

  • RFCs including
  • RFC 2616 for HTTP v1.1,
  • RFC 2068 for pre-v1.1
  • plus others depending on support (compression, URI / URL) and completeness

For a SIMPLE/BASIC/ULTRA-LIGHT HTTP Server, the program flow should be something like that (in pseudo-code):

----Main thread----
Load settings
while true do
    Wait for connection
    Connection received, create a new thread and transfer this connection to this thread.
end

----Connection thread----
Analyze request
if dynamic content do
    Dump the HTTP request and send it to the interpreter
    Wait for response from the interpreter
    Read response header from the interpreter
    Stream response
else if static content do
    Load requested file
    Stream file content
end
(Optional) Cache the response if size < X
Send the response
Close the socket

So you should learn Threading, Interprocess-communication (if you want to interact with an interpreter), Socket programming and the HTTP Protocol.

All details cant be explained here
Visit http://www.linuxhowtos.org/C_C++/socket.htm for creating a basic server using C.
Another one by IBM : http://www.ibm.com/developerworks/systems/library/es-nweb/index.html

You could always start with an existing code base. boa may be a start as it is small, implemented in C and suitable for your 'start on boot' requirement; details are e.g. in the Debian / Ubuntu package.

http://en.wikipedia.org/wiki/Comparison_of_lightweight_web_servers

thank you AGAIN wikipedia

BTW - you might want to Google "embedded web server open source"

(www).ibm.com/developerworks/web/library/wa-ltwebserv/

With libevent library, you can write a web server in 40 lines of c code.

http://www.ruilog.com/article/view/5249.html

If you want create it from ground up, then you can reference open source webserver written in c like lighttpd, apache, nginx.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!