summaryrefslogtreecommitdiff
path: root/Ivy/IvyUDPStreamV4.cs
blob: 4cd5ceeffb35d11d13cb4e0946f0b380c543f3e6 (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
using System;
using System.Collections.Generic;
using System.Text;
using System.Net;
using System.Net.Sockets;
using System.IO;

namespace IvyBus
{
    class IvyUDPStreamV4 : IvyUDPStream
    {
        
        BinaryReader input;
		BinaryWriter output;

        /// the protocol version number
        internal const ushort PROCOCOLVERSION = 4;
		public IvyUDPStreamV4(Socket _socket) : base ( _socket, PROCOCOLVERSION)
		{
            input = new BinaryReader(in_stream, Ivy.ivyEncoding);
            output = new BinaryWriter(out_stream, Ivy.ivyEncoding);
		}
        /*
         * message Syntax:
         * this is a binary formated message use of network representation
         * 
         * message Format:
                protocol_version, TCP server port , lenAppId, appId,  lenAppNameId, appName
         */
        private int DeserializeInt()
        {
            return IPAddress.NetworkToHostOrder((short)input.ReadInt16());
        }
        private string DeserializeString()
        {
            string arg;
            int val_len;
            char[] data;
            val_len = DeserializeInt();
            if (val_len != 0)
            {
                data = input.ReadChars(val_len);
                arg = new String(data);
            }
            else
                arg = string.Empty;
            return arg;
        }

        internal override void Deserialize(out int version, out int port, out string appId, out string appName)
        {
            version = DeserializeInt();
            port = DeserializeInt();
            appId = DeserializeString();
            appName = DeserializeString();

        }
        private void Serialize(int arg)
        {
            output.Write((short)IPAddress.HostToNetworkOrder(arg));
        }
        private void Serialize(string arg)
        {
            ushort length = arg != null ? (ushort)arg.Length : (ushort)0;
            Serialize(length);
            if (length != 0)
                output.Write(arg.ToCharArray());
        }

        internal override void Serialize(int port, string appId, string appName)
        {
            Serialize(PROCOCOLVERSION );
            Serialize(port);
            Serialize(appId);
            Serialize(appName);
            output.Flush();
        }
        
    }
}