1 | #include <stdio.h>
|
---|
2 | #include <net/NetBuffer.h>
|
---|
3 | #include <net/NetEndpoint.h>
|
---|
4 |
|
---|
5 | int32 PingHandler(void* data) {
|
---|
6 | BNetEndpoint* client = (BNetEndpoint*)data;
|
---|
7 | while (true) {
|
---|
8 | int32 size = client->Send("PING\n", 5);
|
---|
9 | snooze(5000000L);
|
---|
10 | }
|
---|
11 | }
|
---|
12 |
|
---|
13 | int32 ConnectionHandler(void* data) {
|
---|
14 | BNetEndpoint* client = (BNetEndpoint*)data;
|
---|
15 | BNetBuffer buffer;
|
---|
16 | bool connection_closed = false;
|
---|
17 | while (!connection_closed) {
|
---|
18 | bool result = client->IsDataPending(10000000L);
|
---|
19 | if (result) {
|
---|
20 | int32 size = client->Receive(buffer, 1024);
|
---|
21 | printf("Got data. Size = %d\n", size);
|
---|
22 | if (size == 0) {
|
---|
23 | printf("Connection closed by remote host.\n");
|
---|
24 | client->Close();
|
---|
25 | delete client;
|
---|
26 | connection_closed = true;
|
---|
27 | }
|
---|
28 | } else {
|
---|
29 | printf("Timeout.\n");
|
---|
30 | }
|
---|
31 | }
|
---|
32 | }
|
---|
33 |
|
---|
34 | void StartConnectionHandler(BNetEndpoint* client) {
|
---|
35 | printf("Starting connection thread.\n");
|
---|
36 | thread_id handler_thread = spawn_thread(ConnectionHandler,
|
---|
37 | "Connection Handler", B_NORMAL_PRIORITY, client);
|
---|
38 | if (handler_thread < B_OK) {
|
---|
39 | printf("Error when spawning connection handler thread.\n");
|
---|
40 | delete client;
|
---|
41 | } else {
|
---|
42 | resume_thread(handler_thread);
|
---|
43 | printf("Connection Handler thread started.\n");
|
---|
44 | }
|
---|
45 |
|
---|
46 | printf("Starting ping thread.\n");
|
---|
47 | thread_id ping_thread = spawn_thread(PingHandler,
|
---|
48 | "Ping Handler", B_NORMAL_PRIORITY, client);
|
---|
49 | if (ping_thread < B_OK) {
|
---|
50 | printf("Error when spawning ping thread.\n");
|
---|
51 | delete client;
|
---|
52 | } else {
|
---|
53 | resume_thread(ping_thread);
|
---|
54 | printf("Ping thread started.\n");
|
---|
55 | }
|
---|
56 |
|
---|
57 | }
|
---|
58 |
|
---|
59 | int main(void) {
|
---|
60 | BNetEndpoint server_port;
|
---|
61 |
|
---|
62 | if (server_port.InitCheck() != B_OK) {
|
---|
63 | printf("Error creating end point.\n");
|
---|
64 | exit (0);
|
---|
65 | }
|
---|
66 |
|
---|
67 | if (server_port.Bind(8080) != B_OK) {
|
---|
68 | printf("Error binding to port 8080 : %s\n", server_port.ErrorStr());
|
---|
69 | exit (0);
|
---|
70 | }
|
---|
71 |
|
---|
72 | if (server_port.Listen() != B_OK) {
|
---|
73 | printf("Error listenning or port 8080 : %s\n", server_port.ErrorStr());
|
---|
74 | exit (0);
|
---|
75 | }
|
---|
76 |
|
---|
77 | while (true) {
|
---|
78 | BNetEndpoint* client = NULL;
|
---|
79 | client = server_port.Accept();
|
---|
80 | printf("Got new connection request.\n");
|
---|
81 | if (client) {
|
---|
82 | StartConnectionHandler(client);
|
---|
83 | }
|
---|
84 | }
|
---|
85 | }
|
---|