"src/turbomind/vscode:/vscode.git/clone" did not exist on "9d75245e65f17fbbca1fdb014b0c6b467af82ed2"
sockets_ex.cpp 1.56 KB
Newer Older
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
/*

    This is an example illustrating the use of the sockets and
    server components from the dlib C++ Library.

    This is a simple echo server.  It listens on port 1234 for incoming
    connections and just echos back any data it receives.  

*/




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

using namespace dlib;
using namespace std;



class serv : public server::kernel_1a_c
{

    void on_connect  (
        connection& con
    )
    {
        char ch;
        while (con.read(&ch,1) > 0)
        {
            // we are just reading one char at a time and writing it back
            // to the connection.  If there is some problem writing the char
            // then we quit the loop.  
            if (con.write(&ch,1) != 1)
                break;
        }
    }

};

serv our_server;

void thread()
{
    cout << "Press enter to end this program" << endl;
    cin.get();
    // this will cause the server to shut down which will in turn cause 
    // our_server.start() to unblock and thus the main() function will terminate.
    our_server.clear();
}



int main()
{
    try
    {
        // create a thread that will listen for the user to end this program
        thread_function t(thread);


        // set up the server object we have made
        our_server.set_listening_port(1234);
        our_server.set_max_connections(1000);

        // start the server
        our_server.start();

    }
    catch (exception& e)
    {
        cout << e.what() << endl;
    }
    catch (...)
    {
        cout << "Some error occurred" << endl;
    }
}