コード例 #1
0
        protected override void ConnectionMade()
        {
            _client = new ConnectedClient();

            _client.ServerId = _parent.ServerId;
            _client.ServerPublicName = _parent.ServerName;

            if (Connection is StreamSocketConnection)
            {
                _client.IPAddress = (Connection as StreamSocketConnection).RemoteEndPoint.Address.ToString();
                _client.Port = (Connection as StreamSocketConnection).RemoteEndPoint.Port;
            }

            using (IdentificationMessage message = new IdentificationMessage())
            {
                AddValueToMessage(message, _client);
                SendMessage(message);
            }

            base.ConnectionMade();

            if (ClientConnected != null)
            {
                ClientConnected(this, new IdentificationEventArgs(_client));
            }
        }
コード例 #2
0
ファイル: AServer.cs プロジェクト: cexcell/AsyncChat
        private async void ProcessClientAsync(TcpClient client)
        {
            var connectedClient = new ConnectedClient();
            try
            {
                connectedClient.TcpClient = client;
                connectedClient.Stream = client.GetStream();
                connectedClient.MessageStream = new MemoryStream();
                connectedClient.Buffer = new byte[64];
                _clients.Add(connectedClient);
            }
            catch (Exception e)
            {
                Console.WriteLine("Error while connecting " + e.Message);
            }

            try
            {
                await ReadAndBroadcast(connectedClient);
            }
            catch (Exception e)
            {
                Console.WriteLine("Error: " + e.Message);
            }
        }
コード例 #3
0
    public async Task ProcessOutgoingDataAsync(ConnectedClient _client)
    {
        var client = _client.Client;
        while (true)
        {

            var stream = client.GetStream();
            //	byte[] length = new byte[4];
            //	await stream.ReadAsync(length,0,4);
            //	int count = BitConverter.ToInt32(length,0);
            //	//stream.Read(buffer,0,count);

            //Packet[] newpackets = Packet.ArrayFromBytes(buffer);

            //JunctionedData.AddRange(newpackets.ToList());
            //Console.WriteLine(BitConverter.ToInt32(newpackets[0].data,0)+" "+newpackets.Length);
            if (_client.ToClientData.Count > 0)
            {
                var outgoing = Packet.ArrayToBytes(_client.ToClientData.ToArray());
                // JunctionedData.AddRange(_client.OutgoingData);
                _client.ToClientData.Clear();
                //stream.Flush();
                SendData(outgoing, client);
            }

        }
    }
コード例 #4
0
	public async Task StartAcceptingConnectionsAsync(){
		while(true){
			var _client = await _server.AcceptTcpClientAsync();
			Console.WriteLine("CLIENT CONNECTED");
			var conclient = new ConnectedClient(_client);
			_clients.Add(conclient);
			Task.Run(()=>{ProcessDataAsync(conclient);});
		}
	}
コード例 #5
0
ファイル: AServer.cs プロジェクト: cexcell/AsyncChat
 private async Task ReadAndBroadcast(ConnectedClient connectedClient, int offset = 0)
 {
     int read = await connectedClient.Stream.ReadAsync(connectedClient.Buffer, offset, connectedClient.Buffer.Length - offset);
     if (read == 0) return;
     connectedClient.MessageStream.Write(connectedClient.Buffer, 0, 5);
     var length = CodedInputStream.CreateInstance(connectedClient.Buffer, 0, 5).ReadRawVarint32();
     var lengthSize = CodedOutputStream.ComputeRawVarint32Size(length);
     int readLeft = (int) (length - 5 + lengthSize);
     var count = Math.Min(read - 5, readLeft);
     await connectedClient.MessageStream.WriteAsync(connectedClient.Buffer, 5, count);
     if (readLeft > read - 5)
     {
         readLeft -= count;
         await ReadWhatLeft(connectedClient, readLeft);
         await ReadAndBroadcast(connectedClient);
     }
     else
     {
         int currentOffset = count + 5;
         while (currentOffset < read - 4)
         {
             var messageSize = CodedInputStream.CreateInstance(connectedClient.Buffer, currentOffset, 5).ReadRawVarint32();
             var intSize = CodedOutputStream.ComputeRawVarint32Size(messageSize);
             int left = (int) (messageSize - 5 + intSize);
             var bufferLeft = read - currentOffset - 5;
             if (left < bufferLeft)
             {
                 await
                     connectedClient.MessageStream.WriteAsync(connectedClient.Buffer, currentOffset + 5,
                         left);
                 currentOffset += 5 + left;
             }
             else
             {
                 await
                     connectedClient.MessageStream.WriteAsync(connectedClient.Buffer, currentOffset + 5,
                         bufferLeft);
                 left -= bufferLeft;
                 await ReadWhatLeft(connectedClient, left);
                 await ReadAndBroadcast(connectedClient);
                 return;
             }
         }
         BroadcastMessage(connectedClient);
         int nextOffset = read - currentOffset;
         for (int i = 0; i < nextOffset; ++i)
         {
             connectedClient.Buffer[i] = connectedClient.Buffer[i + currentOffset];
         }
         await ReadAndBroadcast(connectedClient, nextOffset);
     }
 }
コード例 #6
0
ファイル: MasterCore.cs プロジェクト: darkguy2008/FreeRDC
 public ConnectedClient AddClient(IPEndPoint connection, string fingerprint)
 {
     ConnectedClient c = clients.Where(x => x.HardwareID == fingerprint).SingleOrDefault();
     if (c == null)
     {
         c = new ConnectedClient()
         {
             HardwareID = fingerprint,
             ClientID = GenerateID(),
             Connection = connection,
         };
         clients.Add(c);
     }
     if(connections.Contains(connection))
         connections.Remove(connection);
     return c;
 }
コード例 #7
0
        public void Register()
        {
            var client = CurrentClient;

            lock (_clients)
            {
                if (_clients.ContainsKey(client.ClientId))
                {
                    throw new NDistException("Client has already registered. Register method must be called only once.");
                }

                var monitor = new ConnectedClient(client);
                monitor.Client.Disconnected += Client_Disconnected;

                _clients[client.ClientId] = monitor;
            }

            Console.WriteLine("Registered a new client: " + client.ClientId);
        }
コード例 #8
0
 internal void DeleteFile(string virtualPath)
 {
     ConnectedClient.DeleteFile(virtualPath);
 }
コード例 #9
0
        public ValueTask HandleAsync(ConnectedClient sender, Disconnect message, CancellationToken cancellationToken)
        {
            _store.Remove(sender.ClientId);

            return(sender.Connection.SendAsync(new Disconnected("Requested."), cancellationToken));
        }
コード例 #10
0
ファイル: ServerHandler.cs プロジェクト: marsat02/octoawesome
 private void ServerOnClientConnected(object sender, ConnectedClient e)
 {
     logger.Debug("Hurra ein neuer Spieler");
     e.ServerSubscription         = e.Subscribe(this);
     e.NetworkChannelSubscription = UpdateHub.Subscribe(e, DefaultChannels.Network);
 }
コード例 #11
0
 /// <summary>
 /// Gets the client tag or creates it if necessary.
 /// </summary>
 protected ClientTag GetClientTag(ConnectedClient client)
 {
     return(client.Tag as ClientTag ?? throw new InvalidOperationException("Client tag must not be null."));
 }
コード例 #12
0
 /// <summary>
 /// Performs actions when initializing the connected client.
 /// </summary>
 protected override void OnClientInit(ConnectedClient client)
 {
     client.Tag = new ClientTag();
 }
コード例 #13
0
        /// <summary>
        /// Gets the events.
        /// </summary>
        protected void GetEvents(ConnectedClient client, DataPacket request)
        {
            byte[]     buffer       = request.Buffer;
            int        index        = ArgumentIndex;
            TimeRange  timeRange    = GetTimeRange(buffer, ref index);
            long       dataFilterID = GetInt64(buffer, ref index);
            DataFilter dataFilter   = null;

            if (dataFilterID > 0)
            {
                dataFilter = serverCache.DataFilterCache.Get(dataFilterID);

                if (dataFilter == null)
                {
                    dataFilterID = 0;
                }
            }
            else
            {
                bool useCache = GetBool(buffer, ref index);
                dataFilter = GetDataFilter(typeof(Event), buffer, ref index);

                if (useCache)
                {
                    dataFilterID = serverCache.GetNextID();
                    serverCache.DataFilterCache.Add(dataFilterID, dataFilter);
                }
            }

            int archiveBit = GetByte(buffer, ref index);

            List <Event> events = dataFilter == null ?
                                  new List <Event>() :
                                  archiveHolder.GetEvents(timeRange, dataFilter, archiveBit);
            int totalEventCount = events.Count;
            int blockCount      = totalEventCount > 0 ? (int)Math.Ceiling((double)totalEventCount / EventBlockCapacity) : 1;
            int eventIndex      = 0;

            buffer = client.OutBuf;

            for (int blockNumber = 1; blockNumber <= blockCount; blockNumber++)
            {
                ResponsePacket response = new ResponsePacket(request, buffer);
                index = ArgumentIndex;
                CopyInt32(blockNumber, buffer, ref index);
                CopyInt32(blockCount, buffer, ref index);
                CopyInt64(dataFilterID, buffer, ref index);
                CopyInt32(totalEventCount, buffer, ref index);

                int eventCount = Math.Min(totalEventCount - eventIndex, EventBlockCapacity); // events in this block
                CopyInt32(eventCount, buffer, ref index);

                for (int i = 0; i < eventCount; i++)
                {
                    CopyEvent(events[eventIndex], buffer, ref index);
                    eventIndex++;
                }

                response.BufferLength = index;
                client.SendResponse(response);
            }
        }
コード例 #14
0
ファイル: ServerTerminal.cs プロジェクト: GetRealRenz/ISY
        private void OnClientConnection(IAsyncResult asyn)
        {
            if (m_Closed)
            {
                return;
            }
            try
            {
                Socket clientSocket = m_socket.EndAccept(asyn);
                ConnectedClient connectedClient = new ConnectedClient(clientSocket);

                RaiseClientConnected(clientSocket);
                connectedClient.MessageRecived += OnMessageRecived;
                connectedClient.Disconnected += OnClientDisconnection;

                connectedClient.StartListen();

                long key = clientSocket.Handle.ToInt64();
                if (m_clients.ContainsKey(key))
                {
                    Debug.Fail(string.Format(
                     "Client with handle key '{0}' already exist!", key));
                }
                m_clients[key] = connectedClient;
                m_socket.BeginAccept(new AsyncCallback(OnClientConnection), null);

            }
            catch (ObjectDisposedException odex)
            {
                Debug.Fail(odex.ToString(),
                 "OnClientConnection: Socket has been closed");
            }
            catch (Exception sex)
            {
                Debug.Fail(sex.ToString(),
                "OnClientConnection: Socket failed");
            }
        }
コード例 #15
0
ファイル: Server.cs プロジェクト: alexndrejoly/csharpmlib
 public MessageArrivedArgs(string message, int num, ConnectedClient cl)
 {
     this.message = message;
     this.num = num;
     this.cl = cl;
 }
コード例 #16
0
ファイル: Server.cs プロジェクト: alexndrejoly/csharpmlib
        void Poslusanje()
        {
            listener.Start();
            while (!stopped)
            {
                if ((paused) || (client_num >= maxClients))
                    Thread.Sleep(30);


                TcpClient client = listener.AcceptTcpClient();

                ClientConnectedArgs cca = new ClientConnectedArgs(client_num);
                ClientConnected(this, cca);

                client_num++;

                
                ConnectedClient cl = new ConnectedClient(client);
                clients.Add(cl);
                accepted = false;
                Thread thr = new Thread(Poslusaj);
                thr.IsBackground = true;
                thr.Start();


                while (!accepted)
                    Thread.Sleep(5);

            }
        }
コード例 #17
0
ファイル: Server.cs プロジェクト: alexndrejoly/csharpmlib
 /// <summary>
 /// Sends data to a client
 /// </summary>
 /// <param name="cl">Client</param>
 /// <param name="Message">Message string</param>
 public void SendToClient(ConnectedClient cl, string Message)
 {
     try
     {
         cl.writer.Write(Message);
     }
     catch { StopClient(cl); }
 }
コード例 #18
0
ファイル: Server.cs プロジェクト: alexndrejoly/csharpmlib
        /// <summary>
        /// Disconects the given client
        /// </summary>
        /// <param name="cl">Client</param>
        public void StopClient(ConnectedClient cl)
        {
            try
            {
                cl.client.Close();
            }
            catch { }

            try
            {
                ConnectionClosedArgs cca = new ConnectionClosedArgs(cl);
                ConnectionClosed(this, cca);
            }
            catch { }
        }
コード例 #19
0
 public Task OnClientConnected(ConnectedClient client)
 {
     //_logger.LogInformation("OnClientConnected: {clientId}", client.ClientId);
     return(Task.CompletedTask);
 }
コード例 #20
0
 public override void Handle(ConnectedClient sender, CastSkillCommand message)
 {
     _battleApp.Cast(sender.PlayerId, message.SkillId, new[] { message.TargetId });
 }
コード例 #21
0
 internal IEnumerable <SftpFile> GetContents(string virtualPath)
 {
     return(ConnectedClient.ListDirectory(virtualPath));
 }
コード例 #22
0
 internal void CreateDirectoryInternal(string virtualPath)
 {
     ConnectedClient.CreateDirectory(virtualPath);
 }
コード例 #23
0
ファイル: Server.cs プロジェクト: alexndrejoly/csharpmlib
 public ConnectionClosedArgs(ConnectedClient cl)
 {
     this.cl = cl;
 }
コード例 #24
0
 private void DisconnectClient(ConnectedClient connection)
 {
     connectedClients.Remove(connection);
 }
コード例 #25
0
        internal void HandleIdentificationRequest(IMessage receivedMessage)
        {
            _identification = (receivedMessage as IdentificationMessage).Client;

            using (IdentificationMessage message = new IdentificationMessage())
            {
                _identification.PublicName = _clientName;

                ClientProtocol.AddValueToMessage(message, _identification);

                ClientProtocol.SendMessage(message);

                if (ProtocolMadeConnection != null)
                {
                    ProtocolMadeConnection(this, EventArgs.Empty);
                }

            }
        }
コード例 #26
0
        /// <summary>
        /// Processes the incoming request.
        /// </summary>
        protected override void ProcessCustomRequest(ConnectedClient client, DataPacket request,
                                                     out ResponsePacket response, out bool handled)
        {
            response = null;
            handled  = true;

            switch (request.FunctionID)
            {
            case FunctionID.GetCurrentData:
                GetCurrentData(client, request, out response);
                break;

            case FunctionID.GetTrends:
                GetTrends(client, request);
                break;

            case FunctionID.GetTimestamps:
                GetTimestamps(client, request, out response);
                break;

            case FunctionID.GetSlice:
                GetSlice(client, request, out response);
                break;

            case FunctionID.GetLastWriteTime:
                GetLastWriteTime(client, request, out response);
                break;

            case FunctionID.WriteCurrentData:
                WriteCurrentData(client, request, out response);
                break;

            case FunctionID.WriteHistoricalData:
                WriteHistoricalData(client, request, out response);
                break;

            case FunctionID.GetEventByID:
                GetEventByID(client, request, out response);
                break;

            case FunctionID.GetEvents:
                GetEvents(client, request);
                break;

            case FunctionID.WriteEvent:
                WriteEvent(client, request, out response);
                break;

            case FunctionID.AckEvent:
                AckEvent(client, request, out response);
                break;

            case FunctionID.SendCommand:
                SendCommand(client, request, out response);
                break;

            case FunctionID.GetCommand:
                GetCommand(client, request, out response);
                break;

            case FunctionID.DisableGettingCommands:
                DisableGettingCommands(client, request, out response);
                break;

            default:
                handled = false;
                break;
            }
        }
コード例 #27
0
ファイル: TCP.cs プロジェクト: xh0n9x/Werewolf
 private static void StatusServerOnClientConnected(object sender, ConnectedClient connectedClient)
 {
 }
コード例 #28
0
        /// <summary>
        /// Gets the role name of the connected client.
        /// </summary>
        protected override string GetRoleName(ConnectedClient client)
        {
            Role role = client == null ? null : coreLogic.BaseDataSet.RoleTable.GetItem(client.RoleID);

            return(role == null ? "" : role.Name);
        }
コード例 #29
0
ファイル: TCP.cs プロジェクト: xh0n9x/Werewolf
 private static void ServerOnClientDisconnected(object sender, ConnectedClient tcpClient)
 {
     Program.Log($"Client disconnected: {tcpClient.Client.Client.Handle}");
 }
コード例 #30
0
 public ClientAlreadyConnectedException(ConnectedClient connectedClient)
     : base($"Client {connectedClient.ClientId} is already connected.")
 {
 }
コード例 #31
0
ファイル: TCP.cs プロジェクト: xh0n9x/Werewolf
 private static void ServerOnClientConnected(object sender, ConnectedClient tcpClient)
 {
     Program.Log(
         $"Client connected: {tcpClient.Client.Client.Handle} - {((IPEndPoint) tcpClient.Client.Client.RemoteEndPoint).Address}");
 }
コード例 #32
0
 public DataReceiver(ConnectedClient client)
 {
     _client = client;
     RegisterIntoPipeline();
 }
コード例 #33
0
ファイル: BaseClient.cs プロジェクト: Rogachev99/PUBG
 private void Handler_EndSession(ConnectedClient <T> Client)
 {
     EventEndSession?.Invoke();
 }
コード例 #34
0
 internal Stream CreateFileInternal(string virtualPath)
 {
     return(ConnectedClient.Create(virtualPath));
 }
コード例 #35
0
ファイル: BaseClient.cs プロジェクト: Rogachev99/PUBG
 IController <T> IController <T> .GetNewControler(ConnectedClient <T> client)
 {
     return(this);
 }
コード例 #36
0
 internal SftpFile GetSftpFile(string virtualPath)
 {
     return(ConnectedClient.Get(virtualPath));
 }
コード例 #37
0
 internal void NotifyClientDisconnected(Server.ServerListener listener, ConnectedClient disconnectedClient)
 {
     ClientDisconnected?.Invoke(this, disconnectedClient);
 }
コード例 #38
0
 internal void DeleteDirectory(string virtualPath)
 {
     ConnectedClient.DeleteDirectory(virtualPath);
 }
コード例 #39
0
        private void AcceptCallback(Socket socket, SocketAsyncEventArgs socketAsyncEventArgs)
        {
            // Check for error
            if (socketAsyncEventArgs.SocketError != SocketError.Success)
            {
                HandleCommunicationError(socket, new Exception("Accept failed, error = " + socketAsyncEventArgs.SocketError));
            }

            var handler = socketAsyncEventArgs.AcceptSocket;
            socketAsyncEventArgs.AcceptSocket = null;

            // Post accept on the listening socket
            if (!TryUnsafeSocketOperation(socket, SocketAsyncOperation.Accept, socketAsyncEventArgs))
            {
                throw new Exception("Socket accept failed");
            }

            try
            {
                // Turn on or off Nagle algorithm
                handler.NoDelay = !_useNagleAlgorithm;
                // Set the linger state
                handler.LingerState = _lingerOption;
            }
            catch (SocketException ex)
            {
                HandleCommunicationError(handler, ex);
                return;
            }
            catch (ObjectDisposedException)
            {
                // If disposed, handle communication error was already done and we're just catching up on other threads. suppress it.
                return;
            }

            // If we are at max clients, disconnect
            if (!_maxConnectionsSemaphore.WaitOne(1000))
            {
                handler.Close();
                return;
            }

            // Enroll in currently connected client sockets
            var connectedClient = new ConnectedClient(handler);
            _currentlyConnectedClientsLock.EnterWriteLock();
            try
            {
                _currentlyConnectedClients.Add(connectedClient);
            }
            finally
            {
                _currentlyConnectedClientsLock.ExitWriteLock();
            }

            // Fire the event if needed
            var clientConnected = ClientConnected;
            if (clientConnected != null)
            {
                // Fire the event
                clientConnected(this, EventArgs.Empty);
            }

            // Create receive buffer queue for this client
            _currentlyConnectedClientsReceiveQueuesLock.EnterWriteLock();
            try
            {
                _currentlyConnectedClientsReceiveQueues.Add(handler, new BlockingQueue<SocketAsyncEventArgs>(_maximumConnections * 10));
            }
            finally
            {
                _currentlyConnectedClientsReceiveQueuesLock.ExitWriteLock();
            }

            if (!TryUnsafeSocketOperation(handler, SocketAsyncOperation.Receive, _socketAsyncEventArgsReceivePool.Pop()))
            {
                return;
            }

            ProcessReceivedMessage(connectedClient);
        }
コード例 #40
0
 internal void NotifyClientConnected(Server.ServerListener listener, ConnectedClient newClient)
 {
     ClientConnected?.Invoke(this, newClient);
 }
コード例 #41
0
ファイル: AServer.cs プロジェクト: cexcell/AsyncChat
 private async void BroadcastMessage(ConnectedClient connectedClient)
 {
     foreach (var client in _clients.Where(client => client != connectedClient))
     {
         await connectedClient.Stream.WriteAsync(connectedClient.MessageStream.GetBuffer(), 0, (int) connectedClient.MessageStream.Length);
     }
     connectedClient.MessageStream.SetLength(0);
 }
コード例 #42
0
 public void ShouldContainClientIdInMessage(
     [Frozen] ConnectedClient client,
     ClientAlreadyConnectedException sut)
 {
     Assert.Contains(client.ClientId, sut.Message);
 }
コード例 #43
0
 public List <ConnectedPlayer> getClientPlayers(ConnectedClient c)
 {
     return(players.FindAll(x => x.client.peerID == c.peerID));
 }
コード例 #44
0
        private void HandleIdentificationMessage(IMessage message)
        {
            if (message is IdentificationMessage)
            {
                _client = (message as IdentificationMessage).Client;

                if (ClientIdentified != null)
                {
                    ClientIdentified(this, new IdentificationEventArgs(_client));
                }

                SendFullFileList();
            }
            else throw new InvalidOperationException();
        }
コード例 #45
0
 public DataTransferHandler(Connection connection, ConnectedClient connectedClient)
     : base(connection, connectedClient)
 {
 }
コード例 #46
0
 public CommandHandler(Connection connection, ConnectedClient connectedClient)
     : base(connection, connectedClient)
 {
 }
コード例 #47
0
ファイル: UserConnected.cs プロジェクト: JCFruit/weeb-chat
 public UserConnected(ConnectedClient client)
 {
     Client = client;
 }
コード例 #48
0
        private void ProcessReceivedMessage(ConnectedClient connectedClient)
        {
            int bytesToRead = -1;
            int threadId = -1;

            int availableTest = 0;
            int controlBytesOffset = 0;
            byte[] protocolBuffer = new byte[_controlBytesPlaceholder.Length];
            byte[] resultBuffer = null;

            var handler = connectedClient.Socket;

            BlockingQueue<SocketAsyncEventArgs> receiveBufferQueue = null;
            _currentlyConnectedClientsReceiveQueuesLock.EnterReadLock();
            try
            {
                if (!_currentlyConnectedClientsReceiveQueues.TryGetValue(handler, out receiveBufferQueue))
                {
                    // Peace out!
                    return;
                }
            }
            finally
            {
                _currentlyConnectedClientsReceiveQueuesLock.ExitReadLock();
            }

            // Loop until socket is done
            while (_isListening)
            {
                // If the socket is disposed, we're done
                try
                {
                    availableTest = handler.Available;
                }
                catch (ObjectDisposedException)
                {
                    // Peace out!
                    return;
                }

                // Get the next buffer from the queue
                var socketAsyncEventArgs = receiveBufferQueue.Dequeue();
                if (socketAsyncEventArgs == null)
                {
                    continue;
                }

                var buffer = socketAsyncEventArgs.Buffer;
                int bytesRead = socketAsyncEventArgs.BytesTransferred;

                int currentOffset = 0;

                while (currentOffset < bytesRead)
                {
                    // Check if we need to get our control byte values
                    if (bytesToRead == -1)
                    {
                        var controlBytesNeeded = _controlBytesPlaceholder.Length - controlBytesOffset;
                        var controlBytesAvailable = bytesRead - currentOffset;

                        var controlBytesToCopy = Math.Min(controlBytesNeeded, controlBytesAvailable);

                        // Copy bytes to control buffer
                        Buffer.BlockCopy(buffer, currentOffset, protocolBuffer, controlBytesOffset, controlBytesToCopy);

                        controlBytesOffset += controlBytesToCopy;
                        currentOffset += controlBytesToCopy;

                        // Check if done
                        if (controlBytesOffset == _controlBytesPlaceholder.Length)
                        {
                            // Parse out control bytes
                            ExtractControlBytes(protocolBuffer, out bytesToRead, out threadId);

                            // Reset control bytes offset
                            controlBytesOffset = 0;

                            // Ensure message is not larger than maximum message size
                            if (bytesToRead > _maxMessageSize)
                            {
                                HandleCommunicationError(handler, new InvalidOperationException(string.Format("message of length {0} exceeds maximum message length of {1}", bytesToRead, _maxMessageSize)));
                                return;
                            }
                        }

                        // Continue the loop
                        continue;
                    }

                    // Have control bytes, get message bytes

                    // SPECIAL CASE: if empty message, skip a bunch of stuff
                    if (bytesToRead != 0)
                    {
                        // Initialize buffer if needed
                        if (resultBuffer == null)
                        {
                            resultBuffer = new byte[bytesToRead];
                        }

                        var bytesAvailable = bytesRead - currentOffset;

                        var bytesToCopy = Math.Min(bytesToRead, bytesAvailable);

                        // Copy bytes to buffer
                        Buffer.BlockCopy(buffer, currentOffset, resultBuffer, resultBuffer.Length - bytesToRead, bytesToCopy);

                        currentOffset += bytesToCopy;
                        bytesToRead -= bytesToCopy;
                    }

                    // Check if we're done
                    if (bytesToRead == 0)
                    {
                        if (resultBuffer != null)
                        {
                            // Done, add to complete received messages
                            CompleteMessage(handler, threadId, resultBuffer);

                            // Reset message state
                            resultBuffer = null;
                        }

                        bytesToRead = -1;
                        threadId = -1;

                        connectedClient.LastResponse = DateTime.UtcNow;
                    }
                }

                // Push the buffer back onto the pool
                _socketAsyncEventArgsReceivePool.Push(socketAsyncEventArgs);
            }
        }
コード例 #49
0
ファイル: AServer.cs プロジェクト: cexcell/AsyncChat
 private async Task ReadWhatLeft(ConnectedClient connectedClient, int readLeft)
 {
     while (readLeft > 0)
     {
         int res =
             await
                 connectedClient.Stream.ReadAsync(connectedClient.Buffer, 0,
                     Math.Min(connectedClient.Buffer.Length, readLeft));
         await connectedClient.MessageStream.WriteAsync(connectedClient.Buffer, 0, res);
         readLeft -= res;
     }
     var message = Message.ParseDelimitedFrom(new MemoryStream(connectedClient.MessageStream.GetBuffer(), 0, (int) connectedClient.MessageStream.Length));
     BroadcastMessage(connectedClient);
 }