Exemplo n.º 1
0
        public void ReceiveDataCallback(IAsyncResult AsyncResult)
        {
            string content = String.Empty;

            ConnectionObject connObj        = (ConnectionObject)AsyncResult.AsyncState;
            Socket           FromThisSocket = connObj.SocketObject;

            int BytesRead = FromThisSocket.EndReceive(AsyncResult);

            if (BytesRead > 0)
            {
                if (connObj.IsNewConnection)
                {
                    // Sometimes new connections create some "received" data that doesn't make sense.
                    // So we need to discard these data received.
                    connObj.IsNewConnection = false;
                }
                else
                {
                    connObj.TempStringBuilder.Append(Encoding.UTF8.GetString(connObj.ReceiveBuffer, 0, BytesRead));
                    content = connObj.TempStringBuilder.ToString();

                    // Echo back when seeing CRLF.
                    if (content.IndexOf(Environment.NewLine) > -1)
                    {
                        this.Log(String.Format("Read {0} bytes from client.  Data: [{1}]", content.Length, content));
                        SendData(FromThisSocket, content);
                        connObj.TempStringBuilder.Clear();
                    }
                }

                // Always Keep reading.
                FromThisSocket.BeginReceive(connObj.ReceiveBuffer, 0, Constant.BUFFER_SIZE, SocketFlags.None, new AsyncCallback(ReceiveDataCallback), connObj);
            }
        }
Exemplo n.º 2
0
        public void AcceptConnectionCallback(IAsyncResult AsyncResult)
        {
            // Signal the main thread to continue.
            IsAllDone.Set();

            Socket ListenerSocket = (Socket)AsyncResult.AsyncState;
            Socket AcceptedSocket = ListenerSocket.EndAccept(AsyncResult);

            ConnectionObject ConnObj = new ConnectionObject();

            ConnObj.SocketObject    = AcceptedSocket;
            ConnObj.IsNewConnection = true;

            AcceptedSocket.BeginReceive(ConnObj.ReceiveBuffer, 0, Constant.BUFFER_SIZE, SocketFlags.None, new AsyncCallback(ReceiveDataCallback), ConnObj);
            this.Log(String.Format("Connection from {0} accepted.", ConnObj.SocketObject.RemoteEndPoint.ToString()));
        }