Connecting a C++ server to a browser via sockets

There was an idea to write a server in c++ using the winsock library and connect to it from the browser. That is, in fact, I want to make a website, but give the data to the browser through the server, which takes it from the database. I have heard that it is possible to work with web sockets in js, but is it possible to connect them with winsock sockets? If so, how?

Author: Kromster, 2019-01-06

1 answers

Websocket is probably just not needed in this case. If you want to just "follow the links", then everything is much easier.

To begin with, make a regular server that uses port 80 (although it is probably better to use 8080 for debugging, but this is the case). The server is created in the standard way, via bind/listen/accept, all directly according to any manual.

When the browser accesses your server (enter in the address bar http://127.0.0.1/), to the server something like{[3] will arrive in the socket]}

GET / HTTP/1.1
Host: 127.0.0.1

There may still be a number of fields to fly in, but still the entire request ends with a double line feed (that is, in 0x13 0x10 0x13 0x10). And the lines themselves are separated by a single translation.

OK, the request is easy to parse. The first word is the query type. When "normal walking through the pages" there GET. All sorts of molds are usually POST. The next slash is actually the tail of the resource request (if were requested http://127.0.0.1/index.html, there would be /index.html). Browsers send a resource that starts with a slash, but if you do it yourself, you can do it in different ways. The rest is not important yet.

Now you need to respond to the client. It's a little more complicated here

HTTP/1.1 200 OK
Host: 127.0.0.1
Content-Type: text/html; charset=UTF-8
Connection: close
Content-Length: 2

Hi

The response itself consists of two parts-the header and the body. Parsing line by line

  • first, we tell the client that we are also using the protocol version 1.1 and everything is fine (code 200. OK is a text representation). If the client sent a " bad request, you can send it to for example, 404-the resource is not found), or 500-the server is bad:)
  • then we respond with the host name.
  • then we write what we send. We will have the text.
  • we also say that the connection will be closed after sending the request.
  • and also report the size of the response body. In principle, if the connection is closed, it is not so important, but it is better to write.
  • and then again, a double line feed, so that the client knows where that is
  • Actually the request body itself is two bytes.

That's all, this knowledge is enough to make a simple server.

What to read next?

 2
Author: KoVadim, 2019-01-06 09:46:15