示例#1
0
 public void PadTo32Bits(int len, NetworkSerializer serializer)
 {
     while (((len++) % 4) != 0)
     {
         serializer.Write((byte)0);
     }
 }
示例#2
0
    private void ReadyManager_PollReadyInfoRequest(NetworkPlayer _player)
    {
        var _readyInfo = new List <string>(m_ReadyInfo);

        networkView.RPC("ReadyManager_PollReadyInfoResponse", _player,
                        NetworkSerializer.Serialize(_readyInfo));
    }
示例#3
0
        /// <summary>
        /// Starts the program.
        /// </summary>
        private static void Main()
        {
            IInterprocessSerializer interprocessSerializer = new InterprocessSerializer();
            INetworkSerializer      networkSerializer      = new NetworkSerializer();

            IInterprocessStream interprocessStream =
                new InterprocessStream(DefaultInterprocessStreamName, interprocessSerializer);

            INetworkStream networkStream =
                new NetworkStream(DefaultNetworkStreamName, networkSerializer);

            IMediaSystem mediaSystem =
                new MediaSystem(DefaultMediaSystemName, interprocessStream, networkStream);

            interprocessStream.Start();
            networkStream.Start();

            mediaSystem.Start();
            mediaSystem.WaitForFinished();

            interprocessStream.Stop();
            networkStream.Stop();

            interprocessStream.WaitForFinished();
            networkStream.WaitForFinished();
        }
示例#4
0
        public string GetAttributeKeys(MessageSTUN message)
        {
            string attrKeys = "";

            foreach (KeyValuePair <STUNAttribute, object> entry in message.response)
            {
                string key = Enum.GetName(typeof(STUNAttribute), entry.Key);
                int    id  = (int)entry.Key;
                if (attrKeys.Length > 0)
                {
                    attrKeys += "\n";
                }
                object value    = entry.Value;
                string valueStr = "";
                if (value is string v)
                {
                    valueStr = v;
                }
                else if (value is byte[] b)
                {
                    valueStr = NetworkSerializer.ByteArrayToHexString(b);
                }
                else
                {
                    valueStr = value.ToString();
                }
                attrKeys += key + "(" + id.ToString("X") + ") = " + valueStr;
            }
            return(attrKeys);
        }
        public void __endSendClientRpc(NetworkSerializer serializer, ClientRpcParams clientRpcParams, RpcDelivery rpcDelivery)
#endif
        {
            if (serializer == null)
            {
                return;
            }

            var rpcQueueContainer = NetworkManager.Singleton.RpcQueueContainer;

            if (IsHost)
            {
                ulong[] ClientIds = clientRpcParams.Send.TargetClientIds ?? NetworkManager.Singleton.ConnectedClientsList.Select(c => c.ClientId).ToArray();
                if (clientRpcParams.Send.TargetClientIds != null && clientRpcParams.Send.TargetClientIds.Length == 0)
                {
                    ClientIds = NetworkManager.Singleton.ConnectedClientsList.Select(c => c.ClientId).ToArray();
                }

                var ContainsServerClientId = ClientIds.Contains(NetworkManager.Singleton.ServerClientId);
                if (ContainsServerClientId && ClientIds.Length == 1)
                {
                    rpcQueueContainer.EndAddQueueItemToFrame(serializer.Writer, RpcQueueHistoryFrame.QueueFrameType.Inbound, clientRpcParams.Send.UpdateStage);
                    return;
                }
            }

            rpcQueueContainer.EndAddQueueItemToFrame(serializer.Writer, RpcQueueHistoryFrame.QueueFrameType.Outbound, NetworkUpdateStage.PostLateUpdate);
        }
示例#6
0
            public void NetworkSerialize(NetworkSerializer serializer)
            {
                int paramCount = serializer.IsReading ? 0 : Parameters.Count;

                serializer.Serialize(ref paramCount);

                var paramArray = serializer.IsReading ? new KeyValuePair <int, (AnimatorControllerParameterType Type, object Boxed)> [paramCount] : Parameters.ToArray();
示例#7
0
        NetOutgoingMessage CreateMessage(object contents)
        {
            NetOutgoingMessage msg = server.CreateMessage();

            msg.Write(NetworkSerializer.SerializeObject(contents));
            return(msg);
        }
示例#8
0
        public void __endSendClientRpc(NetworkSerializer serializer, ClientRpcParams clientRpcParams, RpcDelivery rpcDelivery)
#endif
#pragma warning restore IDE1006 // restore naming rule violation check
        {
            if (serializer == null)
            {
                return;
            }

            var rpcQueueContainer = NetworkManager.RpcQueueContainer;

            if (IsHost)
            {
                ulong[] clientIds = clientRpcParams.Send.TargetClientIds ?? NetworkManager.ConnectedClientsList.Select(c => c.ClientId).ToArray();
                if (clientRpcParams.Send.TargetClientIds != null && clientRpcParams.Send.TargetClientIds.Length == 0)
                {
                    clientIds = NetworkManager.ConnectedClientsList.Select(c => c.ClientId).ToArray();
                }

                var containsServerClientId = clientIds.Contains(NetworkManager.ServerClientId);
                if (containsServerClientId && clientIds.Length == 1)
                {
                    rpcQueueContainer.EndAddQueueItemToFrame(serializer.Writer, RpcQueueHistoryFrame.QueueFrameType.Inbound, clientRpcParams.Send.UpdateStage);
                    return;
                }
            }

            rpcQueueContainer.EndAddQueueItemToFrame(serializer.Writer, RpcQueueHistoryFrame.QueueFrameType.Outbound, NetworkUpdateStage.PostLateUpdate);
        }
示例#9
0
    void PlayerManager_RequestUpdateInfo(NetworkPlayer _requestor, string _playerInfoSerial)
    {
        PlayerInfo _player;

        NetworkSerializer.Deserialize(_playerInfoSerial, out _player);

        var _playerLocal = Get(_player.guid);

        if (_playerLocal == null)
        {
            _playerLocal           = _player;
            _playerLocal.connected = false;
            Add(_playerLocal);
            Connect(_playerLocal);
        }
        else
        {
            Copy(_playerLocal, _player);
            if (!_playerLocal.connected)
            {
                Connect(_playerLocal);
            }
        }

        if (postInfoChanged != null)
        {
            postInfoChanged(_player);
        }

        if (Global.Server().server == Network.player.guid)
        {
            networkView.RPC("PlayerManager_ResponseUpdateInfo", _requestor);
        }
    }
示例#10
0
        public void SendMessage(SRActionMessage action)
        {
            NetOutgoingMessage msg = client.CreateMessage();

            msg.Write(NetworkSerializer.SerializeObject(action));
            client.SendMessage(msg, NetDeliveryMethod.ReliableOrdered);
        }
    void TransitionManager_RequestStartGame(string _transitionSerial)
    {
        var _transition = new GameTransition();

        NetworkSerializer.Deserialize(_transitionSerial, out _transition);
        StartGameLocal(_transition);
    }
示例#12
0
        public AgentNetwork(FileInfo fileInfo)
        {
            fileInfo.Refresh();

            if (fileInfo.Exists == false)
            {
                throw new ArgumentException();
            }

            using (FileStream stream = fileInfo.OpenRead())
            {
                var layers     = NetworkSerializer.LoadLayers(new BinaryReader(stream));
                var viewRadius = AgentNetworkInputCoder.EncodedSizeToViewRadius(layers.First().Neurons.First().Weights.Length - 1);
                InputCoder = new AgentNetworkInputCoder(viewRadius);

                if (layers.Last().Neurons.Length != 1)
                {
                    throw new ArgumentException("Invalid neural network shape.");
                }

                if (layers.First().Neurons.First().Weights.Length - 1 != InputCoder.EncodedSize)
                {
                    throw new ArgumentException("Invalid neural network shape.");
                }

                Network = new Network(layers);
            }
        }
示例#13
0
    public void UpdateInfo(Action _callback)
    {
        if (Network.peerType == NetworkPeerType.Disconnected)
        {
            if (_callback != null)
            {
                _callback();
            }
            return;
        }

        m_UpdateInfoCallbacks += _callback;
        if (m_IsUpdatingInfo)
        {
            return;
        }
        m_IsUpdatingInfo = true;
        var _playerInfoSerial = NetworkSerializer.Serialize(mine);

        networkView.RPC("PlayerManager_RequestUpdateInfo", RPCMode.Others, Network.player, _playerInfoSerial);

        if (Network.isServer)
        {
            PlayerManager_ResponseUpdateInfo();
        }
    }
示例#14
0
 public void Save(FileInfo fileInfo)
 {
     using (FileStream stream = fileInfo.OpenWrite())
     {
         NetworkSerializer.SaveLayers(new BinaryWriter(stream), Network.Layers);
     }
 }
    void PlayerManager_InformPlayerInfoChanged(string _playerInfoSerial)
    {
        PlayerInfo _playerInfo;

        NetworkSerializer.Deserialize(_playerInfoSerial, out _playerInfo);
        InformPlayerInfoChangedLocal(_playerInfo);
    }
示例#16
0
        /// <summary>
        ///     Serializes the number of packets lost.
        /// </summary>
        /// <returns>The serialization of the network.</returns>
        public byte[] Serialize()
        {
            var l = new List <byte>(NetworkSerializer.Serialize((uint)Lost));

            l.RemoveAt(0);
            return(l.ToArray());
        }
示例#17
0
        /// <summary>
        ///
        /// </summary>
        public static void FetchFriends(int connectionID, ArraySegmentX <byte> message)
        {
            byte[] bytesArr = new byte[message.Count];
            Buffer.BlockCopy(message.Array, message.Offset, bytesArr, 0, message.Count);

            // Get the text from byte array
            var line = NetworkSerializer.DeserializeText(bytesArr);

            // decompile the data from the text line
            var split = line.Split(',');
            var ids   = new int[split.Length];

            // get the friends ids to verify
            for (int i = 0; i < split.Length; i++)
            {
                if (string.IsNullOrEmpty(split[i]))
                {
                    continue;
                }

                ids[i] = int.Parse(split[i]);
            }

            var cliens  = Program.GetServer().GetAllClients();
            var friends = new FriendData[ids.Length];

            // check if the friends are connected to the server
            for (int i = 0; i < cliens.Length; i++)
            {
                for (int e = 0; e < ids.Length; e++)
                {
                    // if a friend is connected
                    if (ids[e] == cliens[i].AuthID)
                    {
                        // collect their information
                        friends[e] = new FriendData(ids[e]);
                        friends[e].ConnectionID = cliens[i].OwnerID;
                        friends[e].IsOnline     = true;
                    }
                }
            }

            // echo the information of the connected friends to the client who request the information
            string echo = "";

            for (int i = 0; i < friends.Length; i++)
            {
                if (friends[i].Found == false)
                {
                    continue;
                }

                var f = friends[i];
                echo += $"{f.AuthID}|{f.ConnectionID}|{f.IsOnlineBinary()}&";
            }

            //Log.Info($"Fetched friends: {echo}");

            Program.ServerSendToSingle(connectionID, new ArraySegmentX <byte>(NetworkSerializer.SerializeText(echo, ChicasInternalEventType.FetchFriends)));
        }
示例#18
0
        /// <summary>
        ///
        /// </summary>
        public static void SendInvitation(int connectionID, ArraySegmentX <byte> message)
        {
            var text = GetTextFromSegment(message);

            string[] split = text.Split('|');
            int      friendConnectionID = int.Parse(split[0]);
            var      friend             = Program.GetServer().GetClient(friendConnectionID);

            if (friend == null)
            {
                Log.Warning($"Couldn't found client with conID {friendConnectionID}");
                return;
            }

            var sender = Program.GetServer().GetClient(connectionID);

            if (sender == null)
            {
                Log.Warning($"Couldn't found client sender with conID {connectionID}");
                return;
            }
            sender.ProvidedAddress = split[1];

            string data = $"{sender.NickName}|{connectionID}|{sender.AuthID}|{sender.ProvidedAddress}|{split[2]}";

            Program.ServerSendToSingle(friendConnectionID, new ArraySegmentX <byte>(NetworkSerializer.SerializeText(data, ChicasInternalEventType.ReceiveInvitation)));
            Log.Info($"Invitation send to {friend.NickName} from {sender.NickName} to join in {sender.ProvidedAddress}");
        }
示例#19
0
        /// <summary>
        /// Called after the client connect to the server and register his player presence.
        /// </summary>
        public static void CreatePlayer(int connectionID, ArraySegmentX <byte> message)
        {
            byte[] bytesArr = new byte[message.Count];
            Buffer.BlockCopy(message.Array, message.Offset, bytesArr, 0, message.Count);

            var text   = NetworkSerializer.DeserializeText(bytesArr);
            var client = Program.GetServer().GetClient(connectionID);

            // Example text Username|10
            string[] split    = text.Split('|');
            string   nickName = split[0];
            int      id;

            int.TryParse(split[1], out id);

            string echo;

            if (client != null)
            {
                client.NickName = nickName;
                client.AuthID   = id;
                echo            = $"{connectionID}";
                Log.Info($"Player: {nickName}#{id} created and link to connection: {connectionID}");
            }
            else
            {
                echo = "-1";
            }

            Program.ServerSendToSingle(connectionID, new ArraySegmentX <byte>(NetworkSerializer.SerializeText(echo, ChicasInternalEventType.CreatePlayer)));
        }
 public void NetworkSerialize(NetworkSerializer serializer)
 {
     serializer.Serialize(ref ClientId);
     serializer.Serialize(ref PlayerName);
     serializer.Serialize(ref PlayerNum);
     serializer.Serialize(ref SeatState);
     serializer.Serialize(ref SeatIdx);
     serializer.Serialize(ref LastChangeTime);
 }
    public void RequestStartGame(GameTransition _transition)
    {
        if (!Network.isServer)
        {
            Debug.Log("Only server can start the game!");
            return;
        }

        networkView.RPC("TransitionManager_RequestStartGame", RPCMode.All, NetworkSerializer.Serialize(_transition));
    }
    public void RequestStartScene(SceneTransition _transition)
    {
        if (!Network.isServer)
        {
            Debug.Log("Only server is allowed to transfer to scene " + _transition.scene);
            return;
        }

        networkView.RPC("TransitionManager_RequestStartScene", RPCMode.All, NetworkSerializer.Serialize(_transition));
    }
示例#23
0
    private void Awake()
    {
        networkId   = NetworkSerializer.Register(this);
        validEvents = new HashSet <NetworkEventType>(validEventsList);

        if (networkId == UInt16.MaxValue)
        {
            Debug.LogError(this.gameObject.ToString() + " failed network registration!");
        }
    }
        private byte[] EncryptPackage(byte[] data)
        {
            NetworkSerializer serializer = new NetworkSerializer(8192);
            int pkgLength = data.Length;

            serializer.Clear();
            serializer.Write(pkgLength);
            serializer.Write(data);
            return(serializer.ToArray());
        }
示例#25
0
 public void NetworkSerialize(NetworkSerializer serializer)
 {
     serializer.Serialize(ref Index);
     serializer.Serialize(ref EnemyId);
     serializer.Serialize(ref GeneratePointX);
     serializer.Serialize(ref GeneratePointY);
     serializer.Serialize(ref AppearPointX);
     serializer.Serialize(ref AppearPointY);
     serializer.Serialize(ref DisappearPointX);
     serializer.Serialize(ref DisappearPointY);
 }
示例#26
0
 public override byte[] Serialize()
 {
     base.Serialize();
     using var writer = new MemoryStream();
     writer.Write(NetworkSerializer.Serialize(SRC));
     foreach (var i in items)
     {
         writer.Write(i.Serialize());
     }
     return(writer.ToArray());
 }
示例#27
0
 public override byte[] Serialize()
 {
     base.Serialize();
     using var ms = new MemoryStream();
     ms.Write(NetworkSerializer.Serialize(SSRC));
     foreach (var block in RR_Block_list)
     {
         ms.Write(block.Serialize());
     }
     return(ms.ToArray());
 }
示例#28
0
 public void NetworkSerialize(NetworkSerializer serializer)
 {
     if (serializer.IsReading)
     {
         Read(serializer.Reader);
     }
     else
     {
         Write(serializer.Writer);
     }
 }
 void ListenInfoChanged(PlayerInfo _playerInfo)
 {
     if (Network.peerType == NetworkPeerType.Disconnected)
     {
         InformPlayerInfoChangedLocal(_playerInfo);
     }
     else
     {
         var _playerInfoSerial = NetworkSerializer.Serialize(_playerInfo);
         networkView.RPC("PlayerManager_InformPlayerInfoChanged", RPCMode.All, _playerInfoSerial);
     }
 }
示例#30
0
        public void Run()
        {
            // Client initialization
            config = new NetPeerConfiguration("stryferpg");
            client = new NetClient(config);
            client.Start();
            client.Connect("localhost", 1234);

            handler = new LoginMessageHandler();

            // Messages receipt
            NetIncomingMessage message;

            while (!stop)
            {
                while ((message = client.ReadMessage()) != null)
                {
                    switch (message.MessageType)
                    {
                    case NetIncomingMessageType.Data:
                        SROrderMessage msg = NetworkSerializer.DeserializeObject <SROrderMessage>(message.ReadBytes(message.LengthBytes));
                        handler.Handle(msg);
                        break;

                    case NetIncomingMessageType.StatusChanged:
                        switch (message.SenderConnection.Status)
                        {
                        case NetConnectionStatus.Connected:
                            Console.WriteLine("Connected");
                            Console.WriteLine("Asking for server list...");

                            SRActionMessage action = new SRActionMessage(ActionType.GetServerList, ServiceType.Login);
                            SendMessage(action);
                            break;
                        }

                        break;

                    case NetIncomingMessageType.DebugMessage:
                        Console.WriteLine(message.ReadString());
                        break;

                    default:
                        Console.WriteLine("unhandled message with type: "
                                          + message.MessageType);
                        break;
                    }
                }

                Thread.Sleep(1);
            }
        }
        /// <summary>
        /// Loads the network data from file.
        /// </summary>
        public void LoadFromFile(string fileFilter)
        {
            NetworkSerializer serializer = new NetworkSerializer();

            OpenFileDialog dialog = new OpenFileDialog();
            dialog.SupportMultiDottedExtensions = true;
            dialog.Filter = fileFilter;

            if (dialog.ShowDialog() == DialogResult.OK)
            {
                try
                {
                    serializer.LoadNetwork(dialog.FileName, ref _network);
                    MessageBox.Show("File " + dialog.FileName + " loaded",
                                    "File Loaded",
                                    MessageBoxButtons.OK,
                                    MessageBoxIcon.Information);
                }
                catch (Exception ex)
                {
                    StaticClasses.ShowError("Error: Invalid File? " + ex.Message);
                }
            }
        }
        /// <summary>
        /// BrainNet network object to zip stream
        /// </summary>
        /// <param name="network">The network.</param>
        /// <param name="zip">The zip.</param>
        /// <param name="fileName">Name of the file.</param>
        public static void NetworkToZip(INeuralNetwork network, ZipOutputStream zip, string fileName)
        {
            // in this case we have to use a temp file
            string tempFileName = System.IO.Path.GetTempFileName();
            NetworkSerializer serializer = new NetworkSerializer();
            serializer.SaveNetwork(tempFileName, network);

            FileStream fileStream = File.OpenRead(tempFileName);
            byte[] buffer = new byte[fileStream.Length];
            fileStream.Read(buffer, 0, buffer.Length);
            PutZipEntry(zip, buffer, fileName);
            fileStream.Close();

            // cleans up
            File.Delete(tempFileName);
        }
        public INeuralNetwork GetNetwork()
        {
            if (!IsXML) { return null; }

            // in this case we have to use a temp file
            string tempFileName = System.IO.Path.GetTempFileName();
            FileStream fileStream = File.Create(tempFileName);
            fileStream.Write(_buffer, 0, _buffer.Length);
            fileStream.Close();

            NetworkSerializer serializer = new NetworkSerializer();

            //TODO: to be noted, this is not the interface here
            INeuralNetwork network = new NeuralNetwork();
            serializer.LoadNetwork(tempFileName, ref network);

            // cleans up
            File.Delete(tempFileName);

            return network;
        }
        /// <summary>
        /// Save the network data to a file 
        /// </summary>
        public void SaveToFile(string fileFilter, string fileExt, string fileName)
        {
            NetworkSerializer serializer = new NetworkSerializer();

            SaveFileDialog dialog = new SaveFileDialog();
            dialog.SupportMultiDottedExtensions = true;
            dialog.Filter = fileFilter;
            dialog.DefaultExt = fileExt;
            dialog.FileName = fileName;

            if (dialog.ShowDialog() == DialogResult.OK)
            {
                try
                {
                    serializer.SaveNetwork(dialog.FileName, _network);
                    MessageBox.Show("Saved to file " + dialog.FileName,
                                    "File Saved",
                                    MessageBoxButtons.OK,
                                    MessageBoxIcon.Information);
                }
                catch (Exception ex)
                {
                    StaticClasses.ShowError("Error: Invalid File? " + ex.Message);
                }
            }
        }