EndSend() public method

public EndSend ( IAsyncResult asyncResult ) : int
asyncResult IAsyncResult
return int
Example #1
0
        protected void SendCommand(Socket socket, string command, CommandSentEventHandler callback, bool closeConnection = false)
        {
            try
            {
                Wait();
                var byteData = DongleEncoding.Default.GetBytes(command);
                socket.BeginSend(byteData, 0, byteData.Length, 0, asyncResult =>
                {
                    int bytesSent;
                    try
                    {
                        bytesSent = socket.EndSend(asyncResult);
                    }
                    catch (Exception exception)
                    {
                        if (OnErrorOcurred != null)
                        {
                            OnErrorOcurred(exception);
                        }
                        if (OnSocketDisconnected != null)
                        {
                            OnSocketDisconnected(socket);
                        }
                        return;
                    }

                    IsSending = false;

                    if (callback != null)
                    {
                        callback(command, bytesSent);
                    }
                    if (closeConnection)
                    {
                        try
                        {
                            socket.Disconnect(false);
                            if (OnSocketDisconnected != null)
                            {
                                OnSocketDisconnected(socket);
                            }
                        }
                        catch (Exception exception)
                        {
                            if (OnErrorOcurred != null)
                            {
                                OnErrorOcurred(exception);
                            }
                        }                        
                    }
                }, null);
            }
            catch (Exception)
            {                
                if (OnSocketDisconnected != null)
                {
                    OnSocketDisconnected(socket);
                }
            }            
        }
Example #2
0
 private void OnSend(IAsyncResult ar)
 {
     try {
         clientSocket.EndSend(ar);
     }
     catch (ObjectDisposedException) { }
     catch (Exception ex) {
         log("Something went wrong during sending:");
         log(ex.Message);
     }
 }
Example #3
0
 /**
  * Ends asynchronous sending.
  *
  * @param asyncResult
  *   The IAsyncResult returned from the asynchronous sending.
  */
 public void SendCallback(System.IAsyncResult asyncResult)
 {
     try {
         if (penguinSocks.Connected)
         {
             penguinSocks.EndSend(asyncResult);
         }
     }catch (System.Exception sendEx) {
         Out.Logger.WriteOutput("Could not end send to socket: " + sendEx.Message);
     }
 }
Example #4
0
 private void DoSend(IAsyncResult ar)
 {
     try
     {
         System.Net.Sockets.Socket client = (System.Net.Sockets.Socket)ar.AsyncState;
         client.EndSend(ar);
     }
     catch (SocketException ex)
     {
         DoNetworkError(ex);
     }
 }
        private bool SendAsync(byte[] buffer, int offset, int length)
        {
            bool closing = false;

            lock (this)
            {
                Socket socket = this.m_server;
                if (socket == null)
                {
                    closing = true;
                }
                else
                {
                    try
                    {
                        socket.BeginSend(buffer, offset, length, 0, out SocketError error, (ar) =>
                        {
                            try
                            {
                                socket.EndSend(ar, out error);
                                if (error != SocketError.Success)
                                {
                                    closing = true;
                                }
                            }
                            catch (Exception)
                            {
                                closing = true;
                            }
                            if (closing)
                            {
                                this.Close();
                            }
                        }, null);
                        if (error != SocketError.Success && error != SocketError.IOPending)
                        {
                            closing = true;
                        }
                    }
                    catch (Exception)
                    {
                        closing = true;
                    }
                }
            }
            if (closing)
            {
                this.Close();
            }
            return(!closing);
        }
Example #6
0
    private static void OnSent(IAsyncResult ar)
    {
        try
        {
            // Retrieve the socket from the state object.
            System.Net.Sockets.Socket sock = (System.Net.Sockets.Socket)ar.AsyncState;

            // Complete sending the data to the remote device.
            sock.EndSend(ar);
        }
        catch (Exception e)
        {
            Console.WriteLine(e.ToString());
        }
    }
 private void OnSend(IAsyncResult ar)
 {
     try {
         System.Net.Sockets.Socket client = (System.Net.Sockets.Socket)ar.AsyncState;
         if (client == null)
         {
             log("Client is null!");
         }
         client.EndSend(ar);
     }
     catch (Exception ex) {
         log("Something went wrong during sending message.");
         log(ex.Message);
     }
 }
Example #8
0
        /// <summary>
        /// 发送消息完成的回调函数
        /// </summary>
        /// <param name="ar"></param>
        private void OnSendMessageComplete(IAsyncResult ar)
        {
            var         data = ar.AsyncState as byte[];
            SocketError socketError;

            _socket.EndSend(ar, out socketError);
            if (socketError != SocketError.Success)
            {
                _socket.Disconnect(false);
                throw new SocketException((int)socketError);
            }
            if (SendMessageCompleted != null)
            {
                SendMessageCompleted(this, new SocketEventArgs(data));
            }
            //Debug.Log("Send message successful !");
        }
Example #9
0
        void _instance_endSend(IAsyncResult res)
        {
            Core.EventLoop.Instance.Push(() =>
            {
                int nSent = nativeSocket.EndSend(res);

                _bytesWritten += nSent;

                if (onSentCallback != null)
                {
                    Core.EventLoop.Instance.Push(() =>
                    {
                        onSentCallback();
                    });
                }
            });
        }
        /// <summary>
        /// 发送信息
        /// </summary>
        /// <param name="client"></param>
        /// <param name="message"></param>
        public void SendAsync(Socket client, string message) {
            byte[] bytes = System.Text.Encoding.UTF8.GetBytes(message);
            try {

                client.BeginSend(bytes, 0, bytes.Length, SocketFlags.None, ac => {
                    try {
                        int len = client.EndSend(ac);
                    }
                    catch (Exception ex) {
                        ExceptionAction(ex, client);
                    }
                }, null);

            }
            catch (Exception ex) {
                ExceptionAction(ex, client);
            }
        }
Example #11
0
        private static void SendCallback(IAsyncResult ar)
        {
            try
            {
                // Retrieve the socket from the state object.
                System.Net.Sockets.Socket handler = (System.Net.Sockets.Socket)ar.AsyncState;

                // Complete sending the data to the remote device.
                int bytesSent = handler.EndSend(ar);

                handler.Shutdown(SocketShutdown.Both);
                handler.Close();
            }
            catch (Exception)
            {
                throw;
            }
        }
Example #12
0
        private void SendDone(IAsyncResult ar)
        {
            if (!_Socket.Connected)
            {
                return;
            }

            try
            {
                SocketError error;
                var         sendCount = _Socket.EndSend(ar, out error);
                var         task      = (Task)ar.AsyncState;
                task.Done(sendCount);
            }
            catch (Exception e)
            {
                _Enable = false;
            }
        }
Example #13
0
        private void SendCallback(IAsyncResult ar)
        {
            try
            {
                // Retrieve the socket from the state object.
                System.Net.Sockets.Socket handler = (System.Net.Sockets.Socket)ar.AsyncState;

                // Complete sending the data to the remote device.
                int bytesSent = handler.EndSend(ar);
                Console.WriteLine("Sent {0} bytes to client.", bytesSent);

                handler.Shutdown(SocketShutdown.Both);
                handler.Close();
            }
            catch (Exception e)
            {
                Console.WriteLine(e.ToString());
            }
        }
Example #14
0
        private void SendCallback(IAsyncResult ar)
        {
            try
            {
                // Retrieve the socket from the state object.
                System.Net.Sockets.Socket client = (System.Net.Sockets.Socket)ar.AsyncState;

                // Complete sending the data to the remote device.
                int bytesSent = client.EndSend(ar);
                Debug.Log("Sent " + bytesSent + " bytes to server.");

                // Signal that all bytes have been sent.
                // sendDone.Set();
            }
            catch (Exception e)
            {
                Debug.Log(e.ToString());
            }
        }
Example #15
0
        private int _EndSend(IAsyncResult arg)
        {
            SocketError error;
            int         sendCount = Socket.EndSend(arg, out error);

            if (!Socket.Connected)
            {
                _SocketErrorEvent(error);
                return(sendCount);
            }

            if (error == SocketError.Success)
            {
                return(sendCount);
            }

            _SocketErrorEvent(error);
            return(sendCount);
        }
Example #16
0
        private void SendCallback(IAsyncResult ar)
        {
            try
            {
                // Retrieve the socket from the state object.
                System.Net.Sockets.Socket client = (System.Net.Sockets.Socket)ar.AsyncState;

                // Complete sending the data to the remote device.
                int bytesSent = client.EndSend(ar);
                Console.WriteLine("Sent {0} bytes to server.", bytesSent);

                // Signal that all bytes have been sent.
                sendDone.Set();
            }
            catch (Exception e)
            {
                Console.WriteLine(e.ToString());
            }
        }
        /// <summary>
        /// 发送完毕的回调
        /// </summary>
        /// <param name="ar"></param>
        public virtual void SendCallback(IAsyncResult ar)
        {
            System.Net.Sockets.Socket handler = ConnectSocket;
            var sendCallBack = ar.AsyncState as Action <SocketConnection>;

            try
            {
                handler.EndSend(ar); //这里写发送完毕的逻辑
                sendCallBack?.Invoke(this);
            }
            catch (SocketException sktex)
            {
                SocketException(handler, sktex);
            }
            catch (Exception ex)
            {
                Exception(ex);
            }
        }
Example #18
0
        // Handle the end of an asynchronous write.
        // This method is called when an async write is completed. All we
        // do is call through to the core socket EndSend functionality.
        // Returns:  The number of bytes read. May throw an exception.
        public override void EndWrite(IAsyncResult asyncResult)
        {
            ThrowIfDisposed();

            // Validate input parameters.
            if (asyncResult == null)
            {
                throw new ArgumentNullException(nameof(asyncResult));
            }

            try
            {
                _streamSocket.EndSend(asyncResult);
            }
            catch (SocketException socketException)
            {
                throw GetExceptionFromSocketException(SR.Format(SR.net_io_writefailure, socketException.Message), socketException);
            }
            catch (Exception exception) when(!(exception is OutOfMemoryException))
            {
                throw GetCustomException(SR.Format(SR.net_io_writefailure, exception.Message), exception);
            }
        }
Example #19
0
        public override void EndWrite(IAsyncResult ar)
        {
            CheckDisposed();
            if (ar == null)
            {
                throw new ArgumentNullException("async result is null");
            }

            Socket s = socket;

            if (s == null)
            {
                throw new IOException("Connection closed");
            }

            try
            {
                s.EndSend(ar);
            }
            catch (Exception e)
            {
                throw new IOException("EndWrite failure", e);
            }
        }
Example #20
0
 int Utils.Wrappers.Interfaces.ISocket.EndSend(System.IAsyncResult asyncResult)
 {
     return(InternalSocket.EndSend(asyncResult));
 }
Example #21
0
 protected void Send(Socket socket, string data)
 {
     var byteData = Encoding.ASCII.GetBytes(data + "<EOF>");
     socket.BeginSend(byteData, 0, byteData.Length, 0, ar => socket.EndSend(ar), null);
 }
Example #22
0
 private void SendCallback(IAsyncResult ar)
 {
     try
     {
         handler = (Socket)ar.AsyncState;
         int bytesSent = handler.EndSend(ar);
     }
     catch (Exception e)
     {
         Utils.Logger.getInstance.error(e.ToString());
     }
 }
Example #23
0
 private void SendCallback(IAsyncResult ar)
 {
     try
     {
         handler = (Socket)ar.AsyncState;
         int bytesSent = handler.EndSend(ar);
     }
     catch (Exception ex)
     {
         //弹出相关错误事件
         if (OnError != null)
         {
             OnError(ex.HResult.ToString() + "[SendCallback]", ex.Message);
         }
     }
 }
Example #24
0
 private void OnSend(IAsyncResult ar)
 {
     try
     {
         _clientSocket = (Socket)ar.AsyncState;
         _clientSocket.EndSend(ar);
     }
     catch (ObjectDisposedException oex)
     {
         InvokeConnectionServerEvent(new ConnectionServerEventArgs(ConnectionServerEventType.ERROR_OCCURED, "Error during connection  (OnSend, Disposed): " + oex.Message));
     }
     catch (Exception ex)
     {
         InvokeConnectionServerEvent(new ConnectionServerEventArgs(ConnectionServerEventType.ERROR_OCCURED, "Server error | [OnSend]: " + ex.Message));
         ResetSocket(false);
     }
 }
Example #25
0
        static void Main(string[] args)
        {
            var nancyApp = StartupNancyApp();

            //var workingTitleApp = StartupWorkingTitleApp();

            for (;;)
            {
                var input = Console.ReadLine();
                if (input == "exit")
                {
                    nancyApp.Dispose();
                    //workingTitleApp.Dispose();
                    return;
                }

                if (input == "1")
                {
                    var request = (HttpWebRequest)WebRequest.Create("http://127.0.0.1:8080");
                    try
                    {
                        request.GetResponse();
                    }
                    catch (WebException ex)
                    {
                        Console.WriteLine(ex.Message);
                    }
                }
                else if (input == "2")
                {
                    var socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.IP);
                    socket.Connect("localhost", 8080);
                    var blocking = socket.Blocking;
                    socket.Blocking = false;
                    //var sr = socket.BeginReceive(new byte[0], 0, 0, SocketFlags.None, ar =>
                    //                                                                      {
                    //                                                                          socket.EndReceive(ar);
                    //                                                                      }, null);

                    //var optionOutValue = new byte[4];
                    //var ioControl = socket.IOControl(IOControlCode.NonBlockingIO, new byte[] {1, 0, 0, 0}, optionOutValue);
                    unsafe
                    {
                        var wsabuf = new WSABUF();
                        uint numberOfBytesRecvd;
                        var flags = SocketFlags.None;
                        var result = WSARecv(
                            socket.Handle, ref wsabuf, 1, out numberOfBytesRecvd, ref flags, null, CallbackThunk1);

                        var lastError = result == -1 ? Marshal.GetLastWin32Error() : 0;

                        var overlapped = new Overlapped();
                        overlapped.AsyncResult = new ARes();
                        var nativeOverlapped = overlapped.Pack(Iocb, null);
                        Trace.WriteLine(string.Format("{0}", new IntPtr(nativeOverlapped)));

                        wsabuf = new WSABUF {buf = Marshal.AllocCoTaskMem(512), len = 512};
                        var result2 = WSARecv2(
                            socket.Handle,
                            ref wsabuf,
                            1,
                            out numberOfBytesRecvd,
                            ref flags,
                            nativeOverlapped,
                            IntPtr.Zero);
                        var lastError2 = result2 == -1 ? Marshal.GetLastWin32Error() : 0;

                        var data = @"GET / HTTP/1.1
            Host: localhost
            Connection: close

            ".ToArraySegment();
                        SocketError err;
                        socket.BeginSend(
                            data.Array,
                            data.Offset,
                            data.Count,
                            SocketFlags.None,
                            out err,
                            ar =>
                            {
                                socket.EndSend(ar);
                                socket.Shutdown(SocketShutdown.Send);
                            },
                            null);
                    }
                }
                else
                {
                    Console.WriteLine("Known input. Enter exit to exit.");
                }
            }
        }
Example #26
0
        public void OnSend( IAsyncResult ar )
        {
            _socket = (Socket)ar.AsyncState;

            try
            {
                int bytesSent = _socket.EndSend(ar);
                if (bytesSent > 0)
                {

                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "Error processing receive buffer!");
            }
        }
        /// <summary>
        /// Handles the auth request packet.
        /// </summary>
        /// <param name="client">The auth client.</param>
        /// <param name="Packet">The packet.</param>
        public static void Handle(Client.AuthClient client, DataPacket Packet)
        {
            using (var auth = new AuthRequestPacket(Packet))
            {
                Enums.AccountStatus status = Database.ServerDatabase.Authenticate(client, auth.Account, auth.Password);
                client.EntityUID = (uint)ProjectX_V3_Lib.ThreadSafe.RandomGenerator.Generator.Next(1000000, 699999999);

                if (status == Enums.AccountStatus.Ready)
                {
                    try
                    {
                        Database.ServerDatabase.UpdateAuthentication(client);
                        Socket quicksock = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

                        quicksock.Connect(new IPEndPoint(IPAddress.Parse(Program.Config.ReadString("GameIP")), Program.Config.ReadInt32("GameAuthPort")));

                        using (DataPacket packet = new DataPacket(44, 9001))
                        {
                            packet.WriteString(Program.Config.ReadString("ServerPassword"), 4);
                            packet.WriteString(client.Account, 20);
                            packet.WriteInt32(client.DatabaseUID, 36);
                            packet.WriteUInt32(client.EntityUID, 40);
                            quicksock.BeginSend(packet.Copy(), 0, 44, SocketFlags.None,
                                                new AsyncCallback((ia) =>
                                                                  {
                                                                  	int send = quicksock.EndSend(ia);
                                                                  	if (send != 44)
                                                                  	{
                                                                  		status = Enums.AccountStatus.Datebase_Error;
                                                                  		client.EntityUID = 0;
                                                                  	}
                                                                  	Console.WriteLine("Database Notified: [Account: {0}] [DUID: {1}] [EUID: {2}]", client.Account, client.DatabaseUID, client.EntityUID);
                                                                  }), null);

                        }
                        System.Threading.Thread.Sleep(2000);
                    }
                    catch
                    {
                        status = Enums.AccountStatus.Datebase_Error;
                    }
                }

                using (var resp = new AuthResponsePacket())
                {
                    if (status == Enums.AccountStatus.Ready)
                    {
                        Console.WriteLine("Incoming login. [Account: {0}] [Password: {1}]", client.Account, client.Password);

                        resp.EntityUID = client.EntityUID;
                        resp.Port = Program.Config.ReadUInt32("GamePort");
                        resp.IPAddress = Program.Config.ReadString("GameIP");
                    }
                    else
                    {
                        resp.EntityUID = 0;
                    }
                    resp.AccountStatus = status;
                    client.Send(resp);
                }
                System.Threading.Thread.Sleep(5000);
                client.NetworkClient.Disconnect("TIME_OUT");
            }
        }
Example #28
0
 private void sockSendEnd(IAsyncResult ar)
 {
     _Sock = (Socket)ar.AsyncState;
     try
     {
         int bytesSent = _Sock.EndSend(ar);
     }
     catch (Exception e)
     { Console.WriteLine("sndEnd " + e.ToString()); }
 }
Example #29
0
		private void Connect(string serverIp, string name)
		{
			try
			{
				_chatName = name;

				// Initialize socket.
				_clientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);

				// Initialize server IP.
				var serverIP = IPAddress.Parse(serverIp);

				// Initialize the IPEndPoint for the server and use port SERVER_PORT.
				var server = new IPEndPoint(serverIP, ServerInfo.PORT);

				// Initialize the EndPoint for the server.
				_serverEndPoint = server as EndPoint;

				var state = new StateObject()
				{
					Data = new ChatPacket()
					{
						ChatName = _chatName,
						ChatMessage = null,
						ChatDataIdentifier = DataIdentifier.LogIn
					}.Serialize()
				};

				// Send data to server.
				_clientSocket.BeginSendTo(state.Data, 0, state.Data.Length, SocketFlags.None, _serverEndPoint, ar => _clientSocket.EndSend(ar), state);

				// Initialize data stream.
				state = new StateObject();

				// Begin listening for broadcasts from the server.
				_clientSocket.BeginReceiveFrom(state.Data, 0, state.Data.Length, SocketFlags.None, ref _serverEndPoint, EndReceive, state);
			}
			catch (Exception ex)
			{
				Logger.WriteLine("Connection error!");
				Logger.WriteLine(ex.Message);
			}
		}
Example #30
0
        public void OnSend(IAsyncResult ar)
        {
            _socket = (Socket)ar.AsyncState;

            try
            {
                int bytesSent = _socket.EndSend(ar);
                if (bytesSent > 0)
                {
                }
            }
            catch (Exception)
            {
                _textCallback("Error sending data.");
                return;
            }
        }
Example #31
0
        protected void SendFile(Socket socket, FileSentEventHandler callback, byte[] fileData, int offset = 0, int bufferSize = DefaultBufferSize)
        {
            //Wait();
            var sendingLength = bufferSize;
            if (offset + bufferSize > fileData.Length)
            {
                sendingLength = fileData.Length - offset;
            }
            socket.SendTimeout = 1000000;
            socket.BeginSend(fileData, offset, sendingLength, SocketFlags.None, asyncResult =>
            {
                try
                {
                    socket.EndSend(asyncResult);
                }
                catch (Exception exception)
                {
                    if (OnErrorOcurred != null)
                    {
                        OnErrorOcurred(exception);
                    }
                    if (OnSocketDisconnected != null)
                    {
                        OnSocketDisconnected(socket);
                    }
                    return;
                }                

                if (offset + sendingLength < fileData.Length)
                {
                    SendFile(socket, callback, fileData, offset + bufferSize, bufferSize);
                }

                IsSending = false;

                if (callback != null)
                {
                    callback();
                }
            }, null);
        }
Example #32
0
        private void NetworkWrite(ProcessData Processor, SocketPurpose Purpose, Socket NetworkSocket, byte[] Data, int offset, IAsyncResult ar)
        {
            try
            {
                int length = NetworkSocket.EndSend(ar);

                if (length + offset < Data.Length)
                {
                    NetworkSocket.BeginSend(Data, length, Data.Length - (length + offset), SocketFlags.None,
                        delegate(IAsyncResult AsR) { NetworkWrite(Processor, Purpose, NetworkSocket, Data, length + offset, AsR); },
                        null);
                }
                else
                {
                    NetworkSocket.BeginReceive(networkBuf, 0, 1024, SocketFlags.None,
                            delegate(IAsyncResult AsR) { NetworkReceive(Purpose, NetworkSocket, AsR); },
                            null);
                }
            }
            catch (SocketException e)
            {
                OnSocketException(Purpose, NetworkSocket, e);
            }
            catch (ObjectDisposedException)
            {
                OnObjectDisposedException(Purpose, NetworkSocket);
            }
        }
Example #33
0
 protected override int End(System.Net.Sockets.Socket socket, IAsyncResult ar)
 {
     return(socket.EndSend(ar));
 }
Example #34
0
        /// <summary>
        /// 数据发送完成后的处理
        /// </summary>
        /// <returns></returns>
        private bool onSend()
#endif
        {
#if DOTNET2
            System.Net.Sockets.Socket socket = (System.Net.Sockets.Socket)async.AsyncState;
            if (socket == Socket)
            {
                SocketError socketError;
                int count = socket.EndSend(async, out socketError);
                if (socketError == SocketError.Success)
                {
#else
        START:
            if (sendAsyncEventArgs.SocketError == SocketError.Success)
            {
                int count = sendAsyncEventArgs.BytesTransferred;
                System.Net.Sockets.Socket socket;
#endif
                    Data.MoveStart(count);
                    if (Data.Length == 0)
                    {
                        SendSizeLessCount = 0;
                        //isShutdown = true;
                        switch (SendType)
                        {
                            case SendType.Next:
                                if (receiveNext()) return true;
                                break;
                            case SendType.Body:
                                switch (HttpResponse.Type)
                                {
                                    case ResponseType.ByteArray:
                                        Data.Array = HttpResponse.Body.Array;
                                        Data.SetFull();
                                        goto SENDDATA;
                                    case ResponseType.SubByteArray:
                                    case ResponseType.SubBuffer:
                                        Data = HttpResponse.Body;
                                    SENDDATA:
#if DOTNET2
                                        if (socket != Socket) return false;
#else
                                    if ((socket = Socket) == null) return false;
#endif
                                        SendType = SendType.Next;
                                        Timeout = Config.GetTimeout(Data.Length);
#if DOTNET2
                                        async = socket.BeginSend(Data.Array, Data.Start, Data.Length, SocketFlags.None, out socketError, onSendAsyncCallback, socket);
                                        if (socketError == SocketError.Success)
                                        {
                                            if (!async.CompletedSynchronously) Http.Header.ReceiveTimeout.Push(this, socket);
                                            return true;
                                        }
                                        break;
#else
                                    sendAsyncLock.EnterSleepFlag();
                                    sendAsyncEventArgs.SetBuffer(Data.Array, Data.Start, Data.Length);
                                    if (socket.SendAsync(sendAsyncEventArgs))
                                    {
                                        sendAsyncLock.SleepFlag = 0;
                                        Http.Header.ReceiveTimeout.Push(this, socket);
                                        sendAsyncLock.Exit();
                                        return true;
                                    }
                                    sendAsyncLock.ExitSleepFlag();
                                    goto START;
#endif
                                    case ResponseType.File:
                                        SendFileStream = new FileStream(HttpResponse.BodyFile.FullName, FileMode.Open, FileAccess.Read, FileShare.Read, Http.Header.BufferPool.Size, FileOptions.SequentialScan);
                                        if (HttpResponse.State == ResponseState.PartialContent206) SendFileStream.Seek(Header.RangeStart, SeekOrigin.Begin);
                                        SendType = SendType.File;
                                        Buffer.ToSubByteArray(ref Data);
                                        Timeout = Config.GetTimeout(ResponseSize);
                                        goto SENDFILE;
                                }
                                break;
                            case SendType.File:
                            SENDFILE:
#if DOTNET2
                                if (socket != Socket) return false;
#else
                            if ((socket = Socket) == null) return false;
#endif
                                Data.Set(Buffer.StartIndex, (int)Math.Min(ResponseSize, Buffer.Length));
                                if (SendFileStream.Read(Data.Array, Data.Start, Data.Length) == Data.Length)
                                {
                                    if ((ResponseSize -= Data.Length) == 0) SendType = SendType.Next;
#if DOTNET2
                                    async = socket.BeginSend(Data.Array, Data.Start, Data.Length, SocketFlags.None, out socketError, onSendAsyncCallback, socket);
                                    if (socketError == SocketError.Success)
                                    {
                                        if (!async.CompletedSynchronously) Http.Header.ReceiveTimeout.Push(this, socket);
                                        return true;
                                    }
#else
                                sendAsyncLock.EnterSleepFlag();
                                sendAsyncEventArgs.SetBuffer(Data.Start, Data.Length);
                                if (socket.SendAsync(sendAsyncEventArgs))
                                {
                                    sendAsyncLock.SleepFlag = 0;
                                    Http.Header.ReceiveTimeout.Push(this, socket);
                                    sendAsyncLock.Exit();
                                    return true;
                                }
                                sendAsyncLock.ExitSleepFlag();
                                goto START;
#endif
                                }
                                break;
                            case SendType.GetForm:
                                if (getForm()) return true;
                                break;
                        }
                    }
                    else if ((count >= TcpServer.Server.MinSocketSize || (count > 0 && SendSizeLessCount++ == 0)) && AutoCSer.Threading.SecondTimer.Now <= Timeout)
                    {
#if DOTNET2
                        if (socket == Socket)
                        {
                            async = socket.BeginSend(Data.Array, Data.Start, Data.Length, SocketFlags.None, out socketError, onSendAsyncCallback, socket);
                            if (socketError == SocketError.Success)
                            {
                                if (!async.CompletedSynchronously) Http.Header.ReceiveTimeout.Push(this, socket);
                                return true;
                            }
                        }
#else
                    if ((socket = Socket) != null)
                    {
                        sendAsyncLock.EnterSleepFlag();
                        sendAsyncEventArgs.SetBuffer(Data.Start, Data.Length);
                        if (socket.SendAsync(sendAsyncEventArgs))
                        {
                            sendAsyncLock.SleepFlag = 0;
                            Http.Header.ReceiveTimeout.Push(this, socket);
                            sendAsyncLock.Exit();
                            return true;
                        }
                        sendAsyncLock.ExitSleepFlag();
                        goto START;
                    }
#endif
                    }
#if DOTNET2
                }
#endif
            }
            return false;
        }
Example #35
0
        void IProxy.LaunchProxy()
        {
            if (_alreadyCalledProxyMethod)
            {
                return;
            }
            _alreadyCalledProxyMethod = true;

            try
            {

                UdpClient client = new UdpClient(_src);

                Socket server = new Socket(
                        AddressFamily.InterNetwork,
                        SocketType.Dgram,
                        ProtocolType.Udp);
                // ---

                AsyncCallback clientCallback = null;

                AsyncCallback serverCallback = null;

                // TODO: Only done once ... even so, put his in assync! :D
                server.Connect(_target);

                serverCallback = delegate(IAsyncResult res)
                {
                    SocketError err = default(SocketError);
                    int bytes = server.EndSend(res, out err);

                    // Check if all was sent ...
                    if (err == SocketError.Success)
                    {
                        Trace.WriteLine(string.Format("Sent {0} bytes to server.", bytes));
                    }
                    else
                    {
                        Trace.WriteLine(string.Format("Error {0} on sending", err));
                    }

                };

                clientCallback = delegate(IAsyncResult res)
                {
                    // Reattach listener asap

                    client.BeginReceive(clientCallback, client);

                    byte[] datagram = client.EndReceive(res, ref _src);

                    Trace.WriteLine(string.Format("Received {0} bytes from client.", datagram.Length));

                    // Send to target

                    Trace.WriteLine(string.Format("About to send {0} bytes to server", datagram.Length));

                    server.BeginSend(
                            datagram, 0, datagram.Length,
                            SocketFlags.None, serverCallback, server);
                    // --
                };

                IAsyncResult result = client.BeginReceive(clientCallback, client);

            }
            catch (Exception e)
            {
                throw e;
                // TODO: Better exception message ...
                //Trace.WriteLine("Exception at UdpProxy: " + e.Message);
            }
        }