Пример #1
0
        public void SetRemote(string name, object value, bool tcp)
        {
            if (IsClient)
            {
                // if(HasAuthority) {
                lock (Client.Out) {
                    Client.Current.WriteHeader(NetworkData.UpdateField);
                    Client.Out.WriteLong(NetworkId);
                    Client.Out.WriteBool(tcp);
                    Client.Out.WriteString(name);
                    Client.Out.WriteByte(NetworkData.GetObjectType(value));
                    NetworkData.WriteObject(value, Client.Out);
                    if (tcp)
                    {
                        Client.Current.WriteTcp();
                    }
                    else
                    {
                        Client.Current.WriteUdp();
                    }
                }

                /* } else {
                 *  throw new System.InvalidOperationException("Cannot set field without authority");
                 * } */
            }
            else if (IsServer)
            {
                foreach (Socket client in ServerRegistry.Clients.Values)
                {
                    lock (client.Buffer) {
                        client.Buffer.WriteByte(NetworkData.Data);
                        client.Buffer.WriteByte(NetworkData.UpdateField);
                        client.Buffer.WriteLong(NetworkId);
                        client.Buffer.WriteString(name);
                        client.Buffer.WriteByte(NetworkData.GetObjectType(value));
                        NetworkData.WriteObject(value, client.Buffer);
                        if (tcp)
                        {
                            client.WriteBufferTcp();
                        }
                        else
                        {
                            client.WriteBufferUdp();
                        }
                    }
                }
            }
        }
Пример #2
0
        public void PeerConnected(NetPeer peer)
        {
            NetworkData sendData = new NetworkData
            {
                type  = DataRecieveType.serverInitialize,
                other = "Welcome" // peer is already connected
            };

            BinaryFormatter bf = new BinaryFormatter();
            MemoryStream    ms = new MemoryStream();

            bf.Serialize(ms, sendData);
            byte[] data = ms.ToArray();
            Console.WriteLine("Connection from: " + peer.EndPoint);
            peer.Send(data, DeliveryMethod.ReliableOrdered);

            SendConnectedDeveloperData(peer);
        }
Пример #3
0
        public void NetworkRecieve(NetPeer peer, NetPacketReader reader, DeliveryMethod deliveryMethod)
        {
            try
            {
                byte[] data = reader.GetRemainingBytes();

                BinaryFormatter bf = new BinaryFormatter();
                bf.Binder = new DeserializationBinder();
                MemoryStream ms  = new MemoryStream(data);
                NetworkData  rec = (NetworkData)bf.Deserialize(ms);

                Console.WriteLine("Recieved data of type: " + rec.type);
                DealWithRecievedData(rec, peer);
            }
            catch (Exception e)
            {
                Console.WriteLine("Error:\n" + e);
            }
        }
Пример #4
0
        public void InvokeRemote(string name, params object[] args)
        {
            if (IsClient)
            {
                // if(HasAuthority) {
                lock (Client.Out) {
                    Client.Current.WriteHeader(NetworkData.InvokeRPC);
                    Client.Out.WriteLong(NetworkId);
                    Client.Out.WriteString(name);
                    Client.Out.WriteByte((byte)args.Length);
                    foreach (object arg in args)
                    {
                        Client.Out.WriteByte(NetworkData.GetObjectType(arg));
                        NetworkData.WriteObject(arg, Client.Out);
                    }
                    Client.Current.WriteTcp();
                }

                /*} else {
                 *  throw new System.InvalidOperationException("Cannot invoke RPC without authority: " + name);
                 * }*/
            }
            else if (IsServer)
            {
                foreach (Socket client in ServerRegistry.Clients.Values)
                {
                    lock (client.Buffer) {
                        client.Buffer.WriteByte(NetworkData.Data);
                        client.Buffer.WriteByte(NetworkData.InvokeRPC);
                        client.Buffer.WriteLong(NetworkId);
                        client.Buffer.WriteString(name);
                        client.Buffer.WriteByte((byte)args.Length);
                        foreach (object arg in args)
                        {
                            client.Buffer.WriteByte(NetworkData.GetObjectType(arg));
                            NetworkData.WriteObject(arg, client.Buffer);
                        }
                        client.WriteBufferTcp();
                    }
                }
            }
        }
Пример #5
0
        void HandleDeveloperMessage(string msg)
        {
            Console.WriteLine(msg);

            foreach (NetPeer peer in server.ConnectedPeerList)
            {
                BinaryFormatter bf = new BinaryFormatter();
                MemoryStream    ms = new MemoryStream();

                NetworkData dat = new NetworkData
                {
                    type  = DataRecieveType.developerMessage,
                    other = msg
                };
                bf.Serialize(ms, dat);
                byte[] data = ms.ToArray();

                peer.Send(data, DeliveryMethod.ReliableOrdered);
            }
        }
Пример #6
0
        /// <summary>
        /// gives the peer the existing developers
        /// </summary>
        void SendConnectedDeveloperData(NetPeer peer)
        {
            foreach (Developer dev in developers)
            {
                if (null != dev)
                {
                    NetworkData sendData = new NetworkData
                    {
                        type  = DataRecieveType.developerAdd,
                        other = dev
                    };

                    BinaryFormatter bf = new BinaryFormatter();
                    MemoryStream    ms = new MemoryStream();
                    bf.Serialize(ms, sendData);
                    byte[] data = ms.ToArray();
                    Console.WriteLine("Sending developer " + dev.GetName() + " to " + peer.EndPoint);
                    peer.Send(data, DeliveryMethod.ReliableOrdered);
                }
            }
        }
Пример #7
0
        public static void Query(string data, QueryCallback then, params object[] args)
        {
            if (!Side.IsClient)
            {
                throw new InvalidOperationException("Cannot call client-side functions when not on the client");
            }

            Queries[QueryNonce] = then;
            Debug.Log("Querying data: " + data + "...");

            lock (Out) {
                Out.WriteByte(NetworkData.QueryDatabase);
                Out.WriteLong(QueryNonce++);
                Out.WriteString(data);
                Out.WriteByte((byte)args.Length);
                foreach (object arg in args)
                {
                    Out.WriteByte(NetworkData.GetObjectType(arg));
                    NetworkData.WriteObject(arg, Out);
                }

                Current.WriteTcp();
            }
        }
Пример #8
0
        void DeleteDeveloper(NetworkData rec)
        {
            int toDelete = ((Developer)rec.other).GetArrIdx();

            developers[toDelete] = null;

            // put into a function
            // ok now this is actually terrible
            foreach (NetPeer peer in server.ConnectedPeerList)
            {
                BinaryFormatter bf = new BinaryFormatter();
                MemoryStream    ms = new MemoryStream();

                NetworkData dat = new NetworkData
                {
                    type  = DataRecieveType.developerDelete,
                    other = toDelete
                };
                bf.Serialize(ms, dat);
                byte[] data = ms.ToArray();

                peer.Send(data, DeliveryMethod.ReliableOrdered);
            }
        }
Пример #9
0
        void AddNewDeveloper(NetworkData rec)
        {
            Developer newDev = (Developer)rec.other;

            Console.WriteLine("Added new developer: " + newDev.GetName());
            developers[newDev.GetArrIdx()] = newDev;

            // ok now this is actually terrible
            foreach (NetPeer peer in server.ConnectedPeerList)
            {
                BinaryFormatter bf = new BinaryFormatter();
                MemoryStream    ms = new MemoryStream();

                NetworkData dat = new NetworkData
                {
                    type  = DataRecieveType.developerAdd,
                    other = newDev
                };
                bf.Serialize(ms, dat);
                byte[] data = ms.ToArray();

                peer.Send(data, DeliveryMethod.ReliableOrdered);
            }
        }
 public abstract void DealWithRecievedData(NetworkData rec, NetPeer sender);
Пример #11
0
        public Client(string host, int tcpPort, int udpPort)
        {
            NetworkBridge.Log("Creating client...");

            Socket           = new Socket(host, tcpPort, udpPort);
            Current          = this;
            Side.NetworkSide = Side.Client;

            Thread tcpThread = new Thread(() => {
                Stream tcp = Socket.Tcp.GetStream();
                while (!Closed)
                {
                    // NetworkBridge.Log("Waiting to read TCP...");
                    byte[] raw  = new byte[Socket.PacketSize];
                    int read    = tcp.Read(raw, 0, raw.Length);
                    byte[] trim = new byte[read];
                    Array.Copy(raw, 0, trim, 0, trim.Length);

                    if (Closed)
                    {
                        break;
                    }

                    ByteBuffer bufIn = new ByteBuffer(trim);
                    // bufIn.Debug(0, bufIn.Length);
                    // NetworkBridge.Log("Sub-Buffers: ");
                    List <ByteBuffer> buffers = new List <ByteBuffer>();
                    while (bufIn.Pointer != bufIn.Length)
                    {
                        int len        = bufIn.ReadInt();
                        ByteBuffer buf = new ByteBuffer(bufIn.ReadBytes(len));
                        // buf.Debug(0, buf.Length);
                        buffers.Add(buf);
                    }
                    try {
                        // Debug.Log("Executing buffers: ");
                        foreach (ByteBuffer buffer in buffers)
                        {
                            // buffer.Debug(0, buffer.Length);
                            NetworkData.HandleClientData(buffer);
                        }
                    } catch (Exception e) {
                        NetworkBridge.Invoke(() => Debug.LogException(e));
                    }
                }
            });

            tcpThread.IsBackground = true;
            tcpThread.Start();

            Thread udpThread = new Thread(() => {
                while (IsConnected)
                {
                    byte[] raw       = Socket.Udp.Receive(ref Socket.UdpRemote);
                    ByteBuffer bufIn = new ByteBuffer(raw);
                    try {
                        NetworkData.HandleClientData(bufIn);
                    } catch (Exception e) {
                        Debug.LogException(e);
                    }
                }
            });

            udpThread.IsBackground = true;
            udpThread.Start();

            Thread authThread = new Thread(() => {
                Thread.Sleep(100);

                Out.WriteByte(NetworkData.Management);
                Out.WriteByte(NetworkData.Authenticate);
                WriteTcp();

                NetworkBridge.Log("Wrote authentication information.");
            });

            authThread.IsBackground = true;
            authThread.Start();

            OnAuthenticate += (sender, args) => {
                Thread updateThread = new Thread(() => {
                    while (IsConnected)
                    {
                        lock (UdpBuffers) {
                            if (UdpBuffers.Count > 0)
                            {
                                WriteUdp();
                                UdpBuffers.Clear();
                                PositionUpdates.Clear();
                                RotationUpdates.Clear();
                                ScaleUpdates.Clear();
                            }
                        }

                        Thread.Sleep((int)(1000 / (float)TickRate));
                    }
                });
                updateThread.IsBackground = true;
                updateThread.Start();
            };
        }
Пример #12
0
        public Server(ServerConfiguration config)
        {
            Config = config;

            TcpServer = new TcpListener(IPAddress.Any, config.TcpPort);
            UdpServer = new UdpClient(config.UdpPort);

            NetworkBridge.Log("Started TCP and UDP servers.");

            Current = this;

            Thread tcpThread = new Thread(() => {
                TcpServer.Start();

                while (!Closed)
                {
                    TcpClient client = TcpServer.AcceptTcpClient();
                    NetworkBridge.Log("Accepted TCP client.");

                    Socket socket = new Socket(client, null);
                    Stream tcp    = client.GetStream();

                    if (Closed)  // disconnect socket that connected after server closed: is this necessary?
                    {
                        NetworkBridge.Log("Kicked client.");
                        lock (socket.Buffer) {
                            socket.Buffer.WriteByte(NetworkData.Management);
                            socket.Buffer.WriteByte(NetworkData.Disconnect);
                            socket.WriteBufferTcp();
                        }
                        return;
                    }

                    Thread tcpClientThread = new Thread(() => {
                        while (!Closed)
                        {
                            byte[] raw = new byte[Socket.PacketSize];
                            int read   = tcp.Read(raw, 0, raw.Length);

                            if (Closed)
                            {
                                NetworkBridge.Log("Kicked client.");
                                lock (socket.Buffer) {
                                    socket.Buffer.WriteByte(NetworkData.Management);
                                    socket.Buffer.WriteByte(NetworkData.Disconnect);
                                    socket.WriteBufferTcp();
                                }
                                return;
                            }

                            byte[] trimmed = new byte[read];
                            Array.Copy(raw, trimmed, read);

                            ByteBuffer bufIn          = new ByteBuffer(trimmed);
                            List <ByteBuffer> buffers = new List <ByteBuffer>();
                            while (bufIn.Pointer != bufIn.Length)
                            {
                                int len           = bufIn.ReadInt();
                                ByteBuffer buffer = new ByteBuffer(bufIn.ReadBytes(len));
                                buffers.Add(buffer);
                            }
                            try {
                                foreach (ByteBuffer buffer in buffers)
                                {
                                    NetworkData.HandleServerData(buffer, socket);
                                }
                            } catch (Exception e) {
                                NetworkBridge.Invoke(() => Debug.LogException(e));
                            }
                        }
                    });
                    tcpClientThread.IsBackground = true;
                    tcpClientThread.Start();
                }
            });

            tcpThread.IsBackground = true;
            tcpThread.Start();

            Thread udpThread = new Thread(() => {
                IPEndPoint remote = new IPEndPoint(IPAddress.Any, 0);
                while (!Closed)
                {
                    byte[] raw = UdpServer.Receive(ref remote);

                    Socket socket    = new Socket(null, UdpServer);
                    socket.UdpRemote = remote;

                    if (Closed)
                    {
                        return;
                    }

                    ByteBuffer bufIn = new ByteBuffer(raw);
                    byte bufferCount = bufIn.ReadByte();
                    // NetworkBridge.Log("Received " + bufferCount + " buffer(s) of UDP data.");
                    for (int i = 0; i < bufferCount; i++)
                    {
                        byte bufferLength = bufIn.ReadByte();
                        byte[] buffer     = bufIn.ReadBytes(bufferLength);
                        try {
                            NetworkData.HandleServerData(new ByteBuffer(buffer), socket);
                        } catch (Exception e) {
                            NetworkBridge.Invoke(() => UnityEngine.Debug.LogException(e));
                        }
                    }
                }
            });

            udpThread.IsBackground = true;
            udpThread.Start();

            Side.NetworkSide = Side.Server;
        }
Пример #13
0
        public static byte[] Serialize(object obj)
        {
            if (obj == null)
            {
                return(new byte[0]);
            }
            if (obj is ISerializer)
            {
                ISerializer s      = (ISerializer)obj;
                byte[]      serial = s.Serialize();
                byte[]      bytes  = new byte[serial.Length + 2];
                bytes[0] = 1;
                bytes[1] = s.GetSerializerId();
                Array.Copy(serial, 0, bytes, 2, serial.Length);
                return(bytes);
            }
            else if (obj.GetType().IsArray)
            {
                object[] list = (object[])obj;

                ByteBuffer buffer = new ByteBuffer(1024);
                buffer.WriteByte(2);
                buffer.WriteInt(list.Length);
                foreach (object item in list)
                {
                    if (item == null)
                    {
                        buffer.WriteInt(0);
                    }
                    else
                    {
                        byte[] serial = Serialize(item);
                        buffer.WriteInt(serial.Length);
                        buffer.WriteBytes(serial);
                    }
                }

                buffer.Flip();

                return(buffer.Bytes);
            }
            else if (obj is IList)
            {
                IList list = (IList)obj;

                ByteBuffer buffer = new ByteBuffer(1024);
                buffer.WriteByte(3);
                buffer.WriteInt(list.Count);
                foreach (object item in list)
                {
                    if (item == null)
                    {
                        buffer.WriteInt(0);
                    }
                    else
                    {
                        byte[] serial = Serialize(item);
                        buffer.WriteInt(serial.Length);
                        buffer.WriteBytes(serial);
                    }
                }

                buffer.Flip();

                return(buffer.Bytes);
            }
            else if (obj.GetType().IsPrimitive || obj is Vector3 || obj is Quaternion)
            {
                ByteBuffer buf = new ByteBuffer(18); // largest possible object here is a Quaternion, which will be header byte + object type byte + 16 data bytes
                buf.WriteByte(4);
                buf.WriteByte(NetworkData.GetObjectType(obj));
                NetworkData.WriteObject(obj, buf);

                buf.Flip();

                return(buf);
            }

            MemoryStream stream = new MemoryStream();

            Formatter.Serialize(stream, obj);

            return(stream.ToArray());
        }
Пример #14
0
        public static object Deserialize(byte[] obj)
        {
            if (obj.Length > 0)
            {
                if (obj[0] == 1)  // custom-serialized object
                {
                    byte[] data = new byte[obj.Length - 2];
                    Array.Copy(obj, 2, data, 0, data.Length);
                    return(DeserializerRegistry.Deserializers[obj[1]](new ByteBuffer(data)));
                }
                else if (obj[0] == 2)    // array
                {
                    ByteBuffer data = new ByteBuffer(obj);
                    data.Pointer = 1;

                    int      length = data.ReadInt();
                    object[] result = new object[length];

                    for (int i = 0; i < length; i++)
                    {
                        int len = data.ReadInt();
                        if (len == 0)
                        {
                            result[i] = null;
                        }
                        else
                        {
                            result[i] = Deserialize(data.ReadBytes(len));
                        }
                    }

                    return(result);
                }
                else if (obj[0] == 3)    // IList
                {
                    ByteBuffer data = new ByteBuffer(obj);
                    data.Pointer = 1;

                    int           length = data.ReadInt();
                    List <object> result = new List <object>(length);

                    for (int i = 0; i < length; i++)
                    {
                        int len = data.ReadInt();
                        if (len == 0)
                        {
                            result.Add(null);
                        }
                        else
                        {
                            result.Add(Deserialize(data.ReadBytes(len)));
                        }
                    }

                    return(result);
                }
                else if (obj[0] == 4)
                {
                    ByteBuffer data = new ByteBuffer(obj);
                    data.Pointer = 1;

                    byte type = data.ReadByte();
                    return(NetworkData.ReadObject(data, type));
                }

                MemoryStream stream = new MemoryStream();
                stream.Write(obj, 0, obj.Length);

                return(Formatter.Deserialize(stream));
            }
            return(null);
        }