3

I connected to the server with the following code

 web_socket = socket(AF_INET, SOCK_STREAM, 0);
 memset(&server_address, 0, sizeof(struct sockaddr_in));
 inet_pton(AF_inet, "166.111.1.1", &server_address.sin_addr);
 server_address.sin_family = AF_INET;
 server_address.sin_port = htons(8080);
 indicator = connect(web_socket, (struct sockaddr *) &server_address, sizeof(server_address));

The execution of the above code results in indicator being 0, which means connection to the server is successful, but when I tried to write

 string request = "GET http://166.111.1.1:8080/sensor?value=10.3";
 indicator = write(web_socket, request.c_str(), request.length());

I cannot see anything under

 http://166.111.1.1:8080/sensor?value=10.3

or

 http://166.111.1.1:8080/sensor

though the indicator equals to the request length.

Is there anything wrong with the code above? I am testing on Ubuntu 12.04 using QT Creator, GCC

2 Answers 2

2

HTTP request (and reply) headers are terminated with the sequence \r\n\r\n; individual lines within the header are separated with a single \r\n. So what you need is:

string request("GET http://166.111.1.1:8080/sensor?value=10.3\r\n\r\n");

You don't actually need the protocol and IP address in there -- you're already connected -- so this can be reduced to:

string request("GET /sensor?value=10.3\r\n\r\n");

The short version is in fact better (and more normative), because it risks fewer complications with the server.

Sign up to request clarification or add additional context in comments.

Comments

1

You can use boost asio like below:

boost::asio::ip::tcp::iostream  stream;

stream.connect(166.111.1.1, 8080);

stream << "GET /sensor?value=10.3 HTTP/1.1\r\n";
stream << "Accept: */*\r\n";
stream << "Connection: close\r\n";
stream << "\r\n";

1 Comment

Thank you for your response! I avoid using boost because my code need to be transferred here and there so it is inconvenient for me to use external libraries. Actually I just found the solution as referred by goldilocks.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.