Atlas 0.7.0
Networking protocol for the Worldforge system.
example/simple_client.cpp
1/* Simple Atlas-C++ Client
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// Atlas negotiation
11#include <Atlas/Net/Stream.h>
12#include <Atlas/Codec.h>
13// The DebugBridge
14#include "DebugBridge.h"
15
16// tcp_socket_stream - the iostream-based socket class
17#include <skstream/skstream.h>
18
19// cout, cerr
20#include <iostream>
21
22#include <map>
23#include <list>
24
25// sleep()
26#include <unistd.h>
27
28// This sends a very simple message to c
29void helloWorld(Atlas::Codec & c)
30{
31 std::cout << "Sending hello world message... " << std::flush;
32 c.streamMessage();
33 c.mapStringItem("hello", "world");
34 c.mapEnd();
35 std::cout << "done." << std::endl;
36}
37
38int main(int argc, char** argv)
39{
40 // The socket that connects us to the server
41 tcp_socket_stream connection;
42
43 std::cout << "Connecting..." << std::flush;
44
45 // Connect to the server
46 if(argc>1) {
47 connection.open(argv[1], 6767);
48 } else {
49 connection.open("127.0.0.1", 6767);
50 }
51
52 // The DebugBridge puts all that comes through the codec on cout
53 DebugBridge bridge;
54 // Do client negotiation with the server
55 Atlas::Net::StreamConnect conn("simple_client", connection);
56
57 std::cout << "Negotiating... " << std::flush;
58 // conn.poll() does all the negotiation
59 while (conn.getState() == Atlas::Net::StreamConnect::IN_PROGRESS) {
60 conn.poll();
61 }
62 std::cout << "done" << std::endl;
63
64 // Check whether negotiation was successful
65 if (conn.getState() == Atlas::Net::StreamConnect::FAILED) {
66 std::cerr << "Failed to negotiate" << std::endl;
67 return 2;
68 }
69 // Negotiation was successful
70
71 // Get the codec that negotiation established
72 Atlas::Codec * codec = conn.getCodec(bridge);
73
74 // This should always be sent at the beginning of a session
75 codec->streamBegin();
76
77 // Say hello to the server
78 helloWorld(*codec);
79 connection << std::flush;
80
81 std::cout << "Sleeping for 2 seconds... " << std::flush;
82 // Sleep a little
83 sleep(2);
84 std::cout << "done." << std::endl;
85
86 // iosockinet::operator bool() returns false if the connection was broken
87 if (!connection) {
88 std::cout << "Server exited." << std::endl;
89 } else {
90 // It was not broken by the server, so we'll close ourselves
91 std::cout << "Closing connection... " << std::flush;
92 // This should always be sent at the end of a session
93 codec->streamEnd();
94 connection << std::flush;
95 // Close the socket
96 connection.close();
97 std::cout << "done." << std::endl;
98 }
99
100 return 0;
101}