Atlas 0.7.0
Networking protocol for the Worldforge system.
simple_server.cpp
1/* Simple Atlas-C++ Server
2 *
3 * Part of the Atlas-C++ Tutorial
4 *
5 * Copyright 2000 Stefanus Du Toit.
6 *
7 * This file is covered by the GNU Free Documentation License.
8 */
9
10// cout, cerr
11#include <iostream>
12// isockinet, iosockinet - the iostream socket classes
13#include <Atlas/Net/Stream.h>
14// The DebugBridge
15#include "DebugBridge.h"
16#include "sockbuf.h"
17
18extern "C" {
19 #include <stdio.h>
20 #include <sys/time.h>
21 #include <sys/types.h>
22 #include <sys/socket.h>
23 #include <netinet/in.h>
24 #include <unistd.h>
25}
26
27using namespace Atlas;
28using namespace std;
29
30int main(int argc, char** argv)
31{
32 int server_fd = socket(PF_INET, SOCK_STREAM, 0);
33 if (server_fd < 0) {
34 cerr << "ERROR: Could not open socket" << endl << flush;
35 exit(1);
36 }
37 int flag=1;
38 setsockopt(server_fd, SOL_SOCKET, SO_REUSEADDR, &flag, sizeof(flag));
39 struct sockaddr_in sin;
40 sin.sin_family = AF_INET;
41 sin.sin_port = htons(6767);
42 sin.sin_addr.s_addr = 0L;
43 if (bind(server_fd, (struct sockaddr *)&sin, sizeof(sin)) < 0) {
44 close(server_fd);
45 return(-1);
46 }
47 listen(server_fd, 5);
48
49 struct sockaddr_in sin2;
50 unsigned int addr_len = sizeof(sin);
51
52 sin2.sin_family = AF_INET;
53 sin2.sin_port = htons(6767);
54 sin2.sin_addr.s_addr = 0L;
55
56 cout << "Accepting.." << endl << flush;
57 int asock_fd = ::accept(server_fd, (struct sockaddr *)&sin2, &addr_len);
58
59 cout << "accepted client connection!" << endl;
60
61 if (asock_fd < 0) {
62 cerr << "ERROR: Failed to accept socket connection" << endl << flush;
63 exit(1);
64 }
65 sockbuf cli_buf(asock_fd);
66 iostream client(&cli_buf);
67
68 // The DebugBridge puts all that comes through the codec on cout
69 DebugBridge bridge;
70 // Do server negotiation for Atlas with the new client
71 Net::StreamAccept accepter("simple_server", client, &bridge);
72
73 cout << "Negotiating.... " << flush;
74 // accepter.poll() does all the negotiation
75 while (accepter.getState() == Net::StreamAccept::IN_PROGRESS)
76 accepter.poll();
77 cout << "done." << endl;
78
79 // Check the negotiation state to see whether it was successful
80 if (accepter.getState() == Net::StreamAccept::FAILED) {
81 cerr << "Negotiation failed." << endl;
82 return 2;
83 }
84 // Negotiation was successful!
85
86 // Get the codec that negotation established
87 Codec<std::iostream> * codec = accepter.getCodec();
88
89 cout << "Polling client..." << endl;
90
91 // iosockinet::operator bool() returns false once a connection closes
92 while (client) {
93 // Get incoming data and process it
94 codec->poll(); // this blocks!
95 }
96
97 // The connection closed
98
99 cout << "Client exited." << endl;
100
101 return 0;
102}
Definition: sockbuf.h:4
Definition: Bridge.h:20