Atlas  0.7.0
Networking protocol for the Worldforge system.
example/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 // The DebugBridge
11 #include "DebugBridge.h"
12 // Atlas negotiation
13 #include <Atlas/Net/Stream.h>
14 #include <Atlas/Codec.h>
15 // tcp_socket_server, tcp_socket_stream - the iostream socket classes
16 #include <skstream/skserver.h>
17 // cout, cerr
18 #include <iostream>
19 
20 int main(int argc, char** argv)
21 {
22  // This socket accepts connections
23  tcp_socket_server listener;
24 
25  // Bind the socket. 0.0.0.0 accepts on any incoming address
26  listener.open(6767);
27  std::cout << "Bound to " << 6767 << std::endl;
28  std::cout << "Listening... " << std::flush;
29 
30  // This blocks until a client connects
31  tcp_socket_stream client(listener.accept());
32  std::cout << "accepted client connection!" << std::endl;
33 
34  // The DebugBridge puts all that comes through the codec on cout
35  DebugBridge bridge;
36  // Do server negotiation for Atlas with the new client
37  Atlas::Net::StreamAccept accepter("simple_server", client);
38 
39  std::cout << "Negotiating.... " << std::flush;
40  // accepter.Poll() does all the negotiation
41  while (accepter.getState() == Atlas::Net::StreamAccept::IN_PROGRESS) {
42  accepter.poll();
43  }
44  std::cout << "done." << std::endl;
45 
46  // Check the negotiation state to see whether it was successful
47  if (accepter.getState() == Atlas::Net::StreamAccept::FAILED) {
48  std::cerr << "Negotiation failed." << std::endl;
49  return 2;
50  }
51  // Negotiation was successful!
52 
53  // Get the codec that negotation established
54  Atlas::Codec * codec = accepter.getCodec(bridge);
55 
56  std::cout << "Polling client..." << std::endl;
57 
58  // iosockinet::operator bool() returns false once a connection closes
59  while (client) {
60  // Get incoming data and process it
61  codec->poll(); // this blocks!
62  }
63 
64  // The connection closed
65 
66  std::cout << "Client exited." << std::endl;
67 
68  return 0;
69 }