summaryrefslogtreecommitdiff
path: root/comm/test.cc
blob: ac5faca9af5a3e28e127eb862a31b58d02bf9ca4 (plain)
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
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
#include "uch.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#define TESTMSG

#ifdef TESTMSG
class MyRemoteAgent : public IvlRemoteAgent {
public:
	MyRemoteAgent (IvlAgent* a, IvlChannel* ch) : IvlRemoteAgent (a, ch) {}
	~MyRemoteAgent () {}
bool	NewMessage (IvlMsgBuffer&, bool);
};

class MyAgent : public IvlAgent {
public:
	MyAgent (IvlAddress* a) : IvlAgent (a)	{}
	~MyAgent () {}
IvlRemoteAgent*	HandleNew (IvlChannel* ch)	{ return new MyRemoteAgent (this, ch); }
};

class MyMsg : public IvlMessage {
	IvlString	S1;
	IvlString	S2;

public:
	MyMsg (const char* s1, const char* s2) : IvlMessage (), S1 (s1), S2 (s2) {}
	MyMsg () : IvlMessage (), S1 ("S1"), S2 ("S2") {}
	~MyMsg () {}
	void	ReadFrom (IvlMsgBuffer&, lword);
	void	WriteTo (IvlMsgBuffer&);
	void	Dump ()	{ printf ("[%s] [%s]\n", (const char*) S1, (const char*) S2); }
};

bool
MyRemoteAgent :: NewMessage (IvlMsgBuffer& b, bool)
{
	MyMsg m;
	b.Get (m);
	m.Dump ();
	return true;
}

void
MyMsg :: WriteTo (IvlMsgBuffer& b)
{
	b << S1 << S2;
}

void
MyMsg :: ReadFrom (IvlMsgBuffer& b, lword len)
{
	b >> S1 >> S2;
}

#endif

IvlAgent* A;
IvlPortServer* PS;
const char* BUF;

int
fMatch (const char* match, lword host, sword port, const char*)
{
	printf ("0x%lx:%d -> %s\n", host, port, match);
	IvlInetAddress* addr = new IvlInetAddress (host == IvlInetAddress::LoopBack ()
			   					? LOOPBACK : host, port);
	IvlRemoteAgent* ra = A->Contact (addr);
	if (ra) {
		printf ("joined\n");
#ifdef TESTMSG
		MyMsg m ("hello", "world");
		ra->Send (m);
#endif
	} else {
		printf ("connection failed\n");
		delete addr;
	}
	return 1;
}

void
fQuit (int, int)
{
	printf ("quit\n");
	PS->Remove (BUF, *(IvlInetAddress*) A->BoundTo ());
	exit (0);
}

void
fTick (Millisecond t)
{
	printf ("%d\n", t);
}

main (int argc, char** argv)
{
	const char* id = argc > 1 ? argv [1] : "";
	IvlInetAddress addr (ANYADDR);
#ifdef TESTMSG
	MyAgent a (&addr);
#else
	IvlAgent a (&addr);
#endif
	if (a.Setup ()) {
		A = &a;
		IvlPortServer ps ("portserv");
		PS = &ps;
		ps.Match ("portserv:chatty", fMatch);
		char buf [64];
		strcpy (buf, "%s:%u:test");
		strcat (buf, id);
		BUF = buf;
		printf ("registering as %s\n", buf);
		ps.Register (buf, *(IvlInetAddress*) a.BoundTo ());
		IvlSignalHandler h (*a.GetMultiplexer (), SigHup, fQuit);
//		IvlTimeOut to (*a.GetMultiplexer (), 1000, fTick);
		a.Run ();
		ps.Remove (buf, *(IvlInetAddress*) a.BoundTo ());
	}
}