コード例 #1
0
ファイル: ServerConnection.cs プロジェクト: Soarc/Intership
        async Task ReceiveLoopAsync()
        {
            var stream=_client.GetStream();
            var messageLenghtBuffer = new byte[sizeof(int)];

            while (true)
            {
               await stream.ReadAsync(messageLenghtBuffer, 0, messageLenghtBuffer.Length);
               
                var messageLenght = BitConverter.ToInt32(messageLenghtBuffer, 0);

                var messageBuffer = new byte[messageLenght];
                await stream.ReadAsync(messageBuffer, 0, messageLenght);

                var message = new Message();
                message.ReadBytes(messageBuffer);

                if (message.ClientId == 0)
                    ProcessServerMessage(message);
                else
                    ProcessClientMessage(message);

            }

        }
コード例 #2
0
ファイル: ServerConnection.cs プロジェクト: Soarc/Intership
 void ProcessClientMessage(Message message)
 {
     if (MessageReceived != null)
         MessageReceived(message);
 }
コード例 #3
0
ファイル: ServerConnection.cs プロジェクト: Soarc/Intership
        void ProcessServerMessage(Message message)
        {



            //$"ACTION=ActionName;CLIENTID={client.ClientId};NICKNAME={client.Nickname}",
            var messageVariables = message.MessageText.Split(';');

            var variables = messageVariables.Select(x =>
            {

                var parts = x.Split('=');
                var variable = parts[0];
                var value = parts[1];

                return new { Variable = variable, Value = value };

            }).ToArray();


            //if (!_isFirstMessageReceived)
            //{
            //    _clientId = Convert.ToInt32(variables[0].Value);
            //    _isFirstMessageReceived = true;
            //    return;
            //}

            var actionVariable = variables.First(x => x.Variable == "ACTION");

            var action = (ServerActions)Enum.Parse(typeof(ServerActions), actionVariable.Value);




            switch (action)
            {
                case ServerActions.ClientId:
                    var idVariable = variables.First(x => x.Variable == "CLIENTID");
                    _clientId = Convert.ToInt32(idVariable.Value);
                    break;
                case ServerActions.NewClientConnected:
                    var clientId = Convert.ToInt32(variables.First(x => x.Variable == "NEWCLIENTID").Value);
                    var nickName = variables.First(x => x.Variable == "NICKNAME").Value;
                    var user = new User { UserId = clientId, UserNickname = nickName };

                    ConnectedUsers.Add(user);
                    if (NewUserConnected != null)
                        NewUserConnected(user);


                    break;
                case ServerActions.ClientDisconnected:

                    break;
                default:
                    break;
            }












        }