summaryrefslogtreecommitdiffstats
path: root/ml/dlib/examples/server_iostream_ex.cpp
blob: 81fa300111dc0dca57bf0298395356d4040100d3 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
// The contents of this file are in the public domain. See LICENSE_FOR_EXAMPLE_PROGRAMS.txt
/*

    This is an example illustrating the use of the server_iostream object from
    the dlib C++ Library.

    This is a simple echo server.  It listens on port 1234 for incoming
    connections and just echos back any text it receives, but in upper case.  So
    basically it is the same as the sockets_ex.cpp example program  except it
    uses iostreams. 

    To test it out you can just open a command prompt and type:
    telnet localhost 1234

    Then you can type away.

*/




#include <dlib/server.h>
#include <iostream>

using namespace dlib;
using namespace std;



class serv : public server_iostream
{

    void on_connect  (
        std::istream& in,
        std::ostream& out,
        const std::string& foreign_ip,
        const std::string& local_ip,
        unsigned short foreign_port,
        unsigned short local_port,
        uint64 connection_id
    )
    {
        // The details of the connection are contained in the last few arguments to
        // on_connect().  For more information, see the documentation for the
        // server_iostream.  However, the main arguments of interest are the two streams.
        // Here we also print the IP address of the remote machine.
        cout << "Got a connection from " << foreign_ip << endl;

        // Loop until we hit the end of the stream.  This happens when the connection
        // terminates.
        while (in.peek() != EOF)
        {
            // get the next character from the client
            char ch = in.get();

            // now echo it back to them
            out << (char)toupper(ch);
        }
    }

};


int main()
{
    try
    {
        serv our_server;

        // set up the server object we have made
        our_server.set_listening_port(1234);
        // Tell the server to begin accepting connections.
        our_server.start_async();

        cout << "Press enter to end this program" << endl;
        cin.get();
    }
    catch (exception& e)
    {
        cout << e.what() << endl;
    }
}