summaryrefslogtreecommitdiff
path: root/IvyToDel/IvyPPC/IvyUDPStream.cs
blob: 0e3f5179582374b1fb4b0a188d113f49962f66a1 (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
using System;
using System.Collections.Generic;
using System.Text;
using System.Net;
using System.Net.Sockets;
using System.IO;

namespace IvyBus
{
    abstract class IvyUDPStream
    {
        Socket socket;
        byte[] buffer;
   
        protected MemoryStream out_stream;
        protected MemoryStream in_stream;

        ushort protocol_version;

        public ushort ProtocolVersion
        {
            get { return protocol_version; }
        }

        public IvyUDPStream(Socket _socket, ushort protocol) 
		{
            socket = _socket;
            buffer = new byte[4096];
            in_stream = new MemoryStream(buffer);
            out_stream = new MemoryStream();
            protocol_version = protocol;
		}
        internal void Close()
        {
            in_stream.Close();
            out_stream.Close();
            socket.Shutdown(SocketShutdown.Both);
            socket.Close();
        }
        internal void receiveMsg(out IPEndPoint remote, out ushort version, out ushort port, out string appId, out string appName)
        {
            int len;
            IPEndPoint remoteEP = new IPEndPoint(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, ushort 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(ushort port, string appId, string appName);
        abstract internal void Deserialize(out ushort version, out ushort port, out string appId, out string appName);
        
    }
}