MCPcopy Create free account
hub / github.com/davisking/dlib / main

Function main

examples/sockstreambuf_ex.cpp:27–90  ·  view source on GitHub ↗

Source from the content-addressed store, hash-verified

25using namespace dlib;
26
27int main()
28{
29 try
30 {
31 // Connect to Google's web server which listens on port 80. If this
32 // fails it will throw a dlib::socket_error exception. Note that we
33 // are using a smart pointer here to contain the connection pointer
34 // returned from connect. Doing this ensures that the connection
35 // is deleted even if someone throws an exception somewhere in your code.
36 std::unique_ptr<connection> con(connect("www.google.com",80));
37
38
39 {
40 // Create a stream buffer for our connection
41 sockstreambuf buf(con);
42 // Now stick that stream buffer into an iostream object
43 iostream stream(&buf);
44 // This command causes the iostream to flush its output buffers
45 // whenever someone makes a read request.
46 buf.flush_output_on_read();
47
48 // Now we make the HTTP GET request for the main Google page.
49 stream << "GET / HTTP/1.0\r\n\r\n";
50
51 // Here we print each character we get back one at a time.
52 int ch = stream.get();
53 while (ch != EOF)
54 {
55 cout << (char)ch;
56 ch = stream.get();
57 }
58
59 // At the end of this scope buf will be destructed and flush
60 // anything it still contains to the connection. Thus putting
61 // this } here makes it safe to destroy the connection later on.
62 // If we just destroyed the connection before buf was destructed
63 // then buf might try to flush its data to a closed connection
64 // which would be an error.
65 }
66
67 // Here we call close_gracefully(). It takes a connection and performs
68 // a proper TCP shutdown by sending a FIN packet to the other end of the
69 // connection and waiting half a second for the other end to close the
70 // connection as well. If half a second goes by without the other end
71 // responding then the connection is forcefully shutdown and deleted.
72 //
73 // You usually want to perform a graceful shutdown of your TCP connections
74 // because there might be some data you tried to send that is still buffered
75 // in the operating system's output buffers. If you just killed the
76 // connection it might not be sent to the other side (although maybe
77 // you don't care, and in the case of this example it doesn't really matter.
78 // But I'm only putting this here for the purpose of illustration :-).
79 // In any case, this function is provided to allow you to perform a graceful
80 // close if you so choose.
81 //
82 // Also note that the timeout can be changed by supplying an optional argument
83 // to this function.
84 close_gracefully(con);

Callers

nothing calls this directly

Calls 5

connectFunction · 0.85
close_gracefullyFunction · 0.85
flush_output_on_readMethod · 0.80
getMethod · 0.45
whatMethod · 0.45

Tested by

no test coverage detected