Question

Hi I'm a university student and I'm doing a server that writes on a browser. I'm using C language.

I have to write some messages on the browser, I was able to print "HTTP/ 1.1 200 OK" but when I try to print "HTTP/1.1 200 OK" nothing appears in the browser window. I doesn't work.

I must be doing some kind of confusing here. I searched on this site for answers and I saw some people suggesting to use "HTTP/1.1 200 OK\r\n" this also does not work.

I have this sentence in a buffer and I write this directly in the socket connected to the browser with the function write.

write(newsockfd, aux_buffer, tamanho)
Was it helpful?

Solution

Most web applications do not write HTTP directly but use some sort of framework that handles the HTTP communication. However, if you do are interested in writing HTTP directly, you should learn how HTTP works first. For example, a minimal HTTP response might look like this:

HTTP/1.1 200 OK
Content-Type: text/html

<html><head><title>Hello World</title></head><h1>Hello World</h1></html>

Notable here is the HTTP status line and HTTP Headers. The HTTP status line and HTTP Headers are handled by the browser and are normally not shown to the user; the Content-Type header tells the browser that the response body is of MIME text/html (not text/plain or application/xml or image/jpeg or ...), so the browser should use its HTML rendering engine to display the body. There are many HTTP Headers defined by HTTP Specfication (RFC 2616) related to content negotiation, auth, encoding, caching, expiry, redirection, proxying, and many more. The header fields be followed by two newlines, which marks the end of headers fields, and the start of the response body.

Note that for strict conformance to the HTTP spec, the newlines that separates the headers must be \r\n (CR+LF), although HTTP spec recommends (but does not require) that HTTP agents should also recognize other newline styles. Also, the HTTP header must only contain printable US-ASCII characters and may only contain characters from other charset if encoded using RFC 2047. This rule about newline style and US-ASCII encoding only applies to the HTTP header, the response body are free to use other newline styles and encodings.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top