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
|
namespace IvyBus
{
using System;
using System.Collections.Generic;
using System.Text;
using System.Net;
using System.Net.Sockets;
using System.IO;
abstract class IvyUDPStream: IDisposable
{
protected MemoryStream out_stream;
protected MemoryStream in_stream;
private Socket socket;
private byte[] buffer;
private int protocolVersion;
public int ProtocolVersion
{
get { return protocolVersion; }
}
public IvyUDPStream(Socket _socket, int protocol)
{
socket = _socket;
buffer = new byte[4096];
in_stream = new MemoryStream(buffer);
out_stream = new MemoryStream();
protocolVersion = protocol;
}
internal void Close()
{
in_stream.Close();
out_stream.Close();
socket.Shutdown(SocketShutdown.Both);
socket.Close();
}
internal void receiveMsg(out IPEndPoint remote, out int version, out int port, out string appId, out string appName)
{
int len;
IPEndPoint remoteEP = new IPEndPoint(socket.AddressFamily == AddressFamily.InterNetworkV6 ? IPAddress.IPv6Any : IPAddress.Any, 0);
EndPoint tempRemoteEP = (EndPoint)remoteEP;
remoteEP = null;
len = socket.ReceiveFrom(buffer, ref tempRemoteEP);
remote = (IPEndPoint)tempRemoteEP;
in_stream.Position = 0;
in_stream.SetLength(len);
in_stream.Seek(0, SeekOrigin.Begin);
//Call Deserialization
Deserialize( out version, out port, out appId, out appName );
}
internal void sendMsg(IPEndPoint EPhost, int port, string appId, string appName)
{
// Call Serialisation
Serialize(port, appId, appName);
byte[] hellob = out_stream.GetBuffer();
socket.SendTo(hellob, (int)out_stream.Length, 0, EPhost);
}
abstract internal void Serialize(int port, string appId, string appName);
abstract internal void Deserialize(out int version, out int port, out string appId, out string appName);
#region IDisposable Membres
//Implement IDisposable.
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
protected virtual void Dispose(bool disposing)
{
if (disposing)
{
// Free other state (managed objects).
if (out_stream != null)
{
out_stream.Close();
out_stream = null;
}
if (in_stream != null)
{
in_stream.Close();
in_stream = null;
}
}
// Free your own state (unmanaged objects).
// Set large fields to null.
}
#endregion
}
}
|