File: udp.cpp

package info (click to toggle)
dashel 1.3.3-6
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 1,208 kB
  • sloc: cpp: 3,196; ansic: 181; javascript: 15; makefile: 10
file content (95 lines) | stat: -rw-r--r-- 1,939 bytes parent folder | download | duplicates (2)
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
#include <dashel/dashel.h>
#include <iostream>
#include <cassert>

using namespace std;
using namespace Dashel;

class PingServer: public Hub
{
public:
	PingServer()
	{
		listenStream = connect("udp:port=8765");
	}

protected:
	Stream* listenStream;
	map<Stream*, string> nicks;
	
protected:
	virtual void connectionCreated(Stream *stream) { /* hook for use by derived classes */ }
	
	void incomingData(Stream *stream)
	{
		cerr << "new data....";
		PacketStream* packetStream = dynamic_cast<PacketStream*>(stream);
		assert(packetStream);
		IPV4Address source;
		
		packetStream->receive(source);
		cerr << "Ping from " << source.hostname() << ":" << source.port << ": ";
		
		char c;
		while (true)
		{
			packetStream->read(&c, 1);
			if (c)
				cerr << c;
			else
				break;
		}
		cerr << endl;
	}
	
	virtual void connectionClosed(Stream *stream, bool abnormal) { /* hook for use by derived classes */ }
};

class PingClient: public Hub
{
public:
	PingClient(const string& remoteTarget, const string& msg)
	{
		PacketStream* packetStream = dynamic_cast<PacketStream*>(connect("udp:port=8766"));
		assert(packetStream);
		
		packetStream->write(msg.c_str(), msg.length());
		char c = 0;
		packetStream->write(&c, 1);
		
		packetStream->send(IPV4Address(remoteTarget, 8765));
	}
	
protected:
	
	virtual void connectionCreated(Stream *stream) { /* hook for use by derived classes */ }
	
	virtual void incomingData(Stream *stream) { /* hook for use by derived classes */ }
	
	virtual void connectionClosed(Stream *stream, bool abnormal) { /* hook for use by derived classes */ }
};

int main(int argc, char* argv[])
{
	try
	{
		if (argc > 2)
		{
			PingClient client(argv[1], argv[2]);
		}
		else if (argc > 1)
		{
			PingClient client(argv[1], "default message, the other side does lack creativity");
		}
		else
		{
			PingServer().run();
		}
	}
	catch(const DashelException &e)
	{
		std::cerr << e.what() << std::endl;
	}
	
	return 0;
}