-
Notifications
You must be signed in to change notification settings - Fork 0
/
Broadcaster.cs
61 lines (60 loc) · 2.27 KB
/
Broadcaster.cs
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
using System;
using System.Text;
using System.IO;
using System.Net;
using System.Threading;
using System.Net.Sockets;
namespace DistanceVector {
public class Broadcaster {
// Sending to
private Neighbor going { get; set; }
// Receiving from
private Neighbor comming { get; set; }
// Constructor
public Broadcaster(Neighbor comming, Neighbor going) {
this.comming = comming;
this.going = going;
}
// Thread method
public void run() {
String dvs = convert(comming.dv);
Socket sock = null;
bool done = false;
int tries = 0;
// Try five times to send packet, otherwise there is an error
while (!done && tries < 5) {
try {
Thread.Sleep(1000);
IPAddress hostAddress = going.address;
int conPort = going.port;
IPEndPoint hostEndPoint = new IPEndPoint(hostAddress, conPort);
// Connect to router
sock = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
sock.Connect(hostEndPoint);
if (!sock.Connected) {
// Connection failed, try next IPaddress.
sock = null;
break;
}
// Send table
sock.Send(Encoding.UTF8.GetBytes(dvs));
sock.Close();
done = true;
} catch (Exception) {
tries++;
if (tries >= 5)
Console.WriteLine("{0}: Cannot connect to :{1}\nat Address:{2} port:{3} ", comming.id, going.id, going.address, going.port);
}
}
}
// Convert table into string for UTF writing with the coming from id on the end
public String convert(int[] dv) {
// Fix offset for spaces following
String result = dv[0] + "";
for (int i = 1; i < dv.Length; i++) {
result += " " + dv[i];
}
return (result+" "+comming.id);
}
}
}