Dispose() 공개 메소드

public Dispose ( ) : void
리턴 void
		public void Defaults ()
		{
			SocketAsyncEventArgs saea = new SocketAsyncEventArgs ();
			Assert.IsNull (saea.AcceptSocket, "AcceptSocket");
			Assert.IsNull (saea.Buffer, "Buffer");
			Assert.IsNull (saea.BufferList, "BufferList");
			Assert.AreEqual (0, saea.BytesTransferred, "BytesTransferred");
			Assert.AreEqual (0, saea.Count, "Count");
			Assert.IsFalse (saea.DisconnectReuseSocket, "DisconnectReuseSocket");
			Assert.AreEqual (SocketAsyncOperation.None, saea.LastOperation, "LastOperation");
			Assert.AreEqual (0, saea.Offset, "Offset");
			Assert.IsNull (saea.RemoteEndPoint, "RemoteEndPoint");
#if !MOBILE
			Assert.IsNotNull (saea.ReceiveMessageFromPacketInfo, "ReceiveMessageFromPacketInfo");
			Assert.IsNull (saea.SendPacketsElements, "SendPacketsElements");
			Assert.AreEqual (TransmitFileOptions.UseDefaultWorkerThread, saea.SendPacketsFlags, "SendPacketsFlags");
#endif
			Assert.AreEqual (-1, saea.SendPacketsSendSize, "SendPacketsSendSize");
			Assert.AreEqual (SocketError.Success, saea.SocketError, "SocketError");
			Assert.AreEqual (SocketFlags.None, saea.SocketFlags, "SocketFlags");
			Assert.IsNull (saea.UserToken, "UserToken");

			saea.Dispose ();
			saea.Dispose (); // twice
		}
예제 #2
0
		public void ConnectTo(string ip, int port)
		{

			State = ConnectionState.NotConnected;

			socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

			IPAddress[] ips = Dns.GetHostAddresses(ip);
			var addr = ips[0];
			var hostEndPoint = new IPEndPoint(addr, port);

			var connectEA = new SocketAsyncEventArgs();

			connectEA.RemoteEndPoint = hostEndPoint;
			connectEA.Completed += (object sender, SocketAsyncEventArgs e)=>{

				switch (e.LastOperation)
				{
				case SocketAsyncOperation.Connect:
					UnityEngine.Debug.Log("Connect success");
					break;
				default:
					throw new ArgumentException("The last operation completed on the socket was not a receive or send");
				}

				connectEA.Dispose();

				State = ConnectionState.Connected;

			};

			State = ConnectionState.Connecting;

			socket.ConnectAsync(connectEA);
		}
예제 #3
0
        /// <summary>
        /// Create a UdpCommunication object using an existing Socket.
        /// </summary>
        public UdpCommunication(Socket socket, IPEndPoint endPoint)
        {
            _socket = socket;
            _endPoint = endPoint;

            // Start asynchronous read
            try
            {
                _receiveArgs = new SocketAsyncEventArgs();
                _receiveArgs.UserToken = _socket;
                _receiveArgs.RemoteEndPoint = _endPoint;
                _readBuffer = new byte[READBUFFERSIZE];
                _receiveArgs.SetBuffer(_readBuffer, 0, _readBuffer.Length);
                _receiveArgs.Completed += new EventHandler<SocketAsyncEventArgs>(_socket_ReceivedData);
                if (_socket.ReceiveFromAsync(_receiveArgs) == false)  // Returns true if the I/O operation is pending. Returns false if the I/O operation completed synchronously and the SocketAsyncEventArgs.Completed event will not be raised.
                    _socket_ReceivedData(_socket, _receiveArgs);
            }
            catch (Exception ex)
            {
                // On failure free up the SocketAsyncEventArgs
                if (_receiveArgs != null)
                {
                    _receiveArgs.Completed -= new EventHandler<SocketAsyncEventArgs>(_socket_ReceivedData);
                    _receiveArgs.Dispose();
                    _receiveArgs = null;
                }

                throw;
            }
        }
예제 #4
0
파일: UdpSocket.cs 프로젝트: noex/RSSDP
        public System.Threading.Tasks.Task<ReceivedUdpData> ReceiveAsync()
        {
            ThrowIfDisposed();

            var tcs = new TaskCompletionSource<ReceivedUdpData>();

            var socketEventArg = new SocketAsyncEventArgs();
            try
            {
                socketEventArg.RemoteEndPoint = new IPEndPoint(IPAddress.Any, 0);
                socketEventArg.UserToken = tcs;

                socketEventArg.SetBuffer(new Byte[SsdpConstants.DefaultUdpSocketBufferSize], 0, SsdpConstants.DefaultUdpSocketBufferSize);

                socketEventArg.Completed += socketEventArg_ReceiveCompleted;

                _Socket.ReceiveAsync(socketEventArg);
            }
            catch
            {
                socketEventArg.Dispose();

                throw;
            }

            return tcs.Task;
        }
예제 #5
0
        void Complete(SocketAsyncEventArgs e, bool completeSynchronously)
        {
            TransportBase transport = null;
            Exception exception = null;
            if (e.SocketError != SocketError.Success)
            {
                exception = new SocketException((int)e.SocketError);
                if (e.AcceptSocket != null)
                {
                    e.AcceptSocket.Close(0);
                }
            }
            else
            {
                Fx.Assert(e.AcceptSocket != null, "Must have a valid socket accepted.");
                transport = new TcpTransport(e.AcceptSocket, this.transportSettings);
                transport.Open();
            }

            e.Dispose();
            this.callbackArgs.CompletedSynchronously = completeSynchronously;
            this.callbackArgs.Exception = exception;
            this.callbackArgs.Transport = transport;

            if (!completeSynchronously)
            {
                this.callbackArgs.CompletedCallback(this.callbackArgs);
            }
        }
예제 #6
0
        static void Accept_Completed(object sender, SocketAsyncEventArgs e)
        {
            Socket client = e.AcceptSocket;
             Socket server = sender as Socket;

             if (sender == null) return;

             SocketAsyncEventArgs sendArg = new SocketAsyncEventArgs();
             SocketAsyncEventArgs receciveArg = new SocketAsyncEventArgs();

             ConnectInfo info = new ConnectInfo();
             info.tmpList = new ArrayList();
             info.SendArg = sendArg;
             info.ReceiveArg = receciveArg;
             info.ServerSocket=server;

             byte[] sendbuffers=Encoding.ASCII.GetBytes("welcome\n");
             sendArg.SetBuffer(sendbuffers, 0, sendbuffers.Length);

             sendbuffers=new byte[1024];
             receciveArg.SetBuffer(sendbuffers, 0, 1024);
             receciveArg.UserToken = info;
             receciveArg.Completed += new EventHandler<SocketAsyncEventArgs>(Rececive_Completed);

             client.SendAsync(sendArg);
             client.ReceiveAsync(receciveArg);

             e.Dispose();
        }
예제 #7
0
 public static void FreeScEv(SocketAsyncEventArgs buf)
 {
     if (_evPool == null) {
         return;
     }
     if (!_evPool.FreeObj(buf)) {
         buf.Dispose();
     }
 }
예제 #8
0
        private void TMNRPCClient_SocketError(object sender, SocketErrorEventArgs e)
        {
            SocketAsyncEventArgs.Dispose();
            SocketAsyncEventArgs = null;

            if (e.SocketError == System.Net.Sockets.SocketError.ConnectionReset && ServerClosedConnection != null)
            {
                ServerClosedConnection(this, EventArgs.Empty);
            }
        }
예제 #9
0
 public void Release(SocketAsyncEventArgs args)
 {
     lock (_pool)
     {
         if (args.Buffer.Equals(_buffer))
             _pool.Push(args);
         else
             args.Dispose();
     }
     _acquisitionGate.Release();
 }
예제 #10
0
        private void EndSend(object sender, SocketAsyncEventArgs pArguments)
        {
            if (mDisconnected != 0) return;

            if (pArguments.BytesTransferred <= 0)
            {
                Disconnect();
                return;
            }

            ByteArraySegment segment;
            if (sendSegments.TryPeek(out segment))
            {
                if (segment.Advance(pArguments.BytesTransferred))
                {
                    ByteArraySegment seg;
                    sendSegments.TryDequeue(out seg); //we try to get it out
                }

                if (sendSegments.Count > 0)
                {
                    this.BeginSend();
                }
                else
                {
                    mSending = 0;
                }
            }
            pArguments.Dispose(); //clears out the whole async buffer
        }
예제 #11
0
        private void ApplyReceiveWorkaround()
        {
            _logger.Trace("Applying receive workaround for WP7");

            var waitEvent = new ManualResetEvent(false);
            var tempEventArgs = new SocketAsyncEventArgs();
            tempEventArgs.SetBuffer(new byte[] { 0xff }, 0, 1);
            tempEventArgs.RemoteEndPoint = _socketOperation.RemoteEndPoint;
            tempEventArgs.Completed += (s, e) => waitEvent.Set();
            _currentSocket.SendToAsync(tempEventArgs);
            waitEvent.WaitOne();
            waitEvent.Dispose();
            tempEventArgs.Dispose();

            _receiveWorkaroundApplied = true;
        }
예제 #12
0
        private void onConnected(object sender, SocketAsyncEventArgs e)
        {
            ((ManualResetEvent)e.UserToken).Set();

            e.Dispose();
        }
예제 #13
0
        private void AcceptCompleted(object sender, SocketAsyncEventArgs e)
        {
            try
            {
                var clientSocket = e.AcceptSocket;
                Logger.WriteLine("Client connected!");
                var client = this.CreateNewClient(clientSocket);
                this.OnClientConnected(new ClientConnectedEventArgs(client));

                client.WaitForClientData();

                this.WaitForClientConnect();
            }
            catch (global::System.ObjectDisposedException)
            {
                Logger.WriteLine("OnClientConnection: Socket has been closed!", TraceEventType.Information);
            }
            catch (SocketException se)
            {
                Logger.WriteLine("SocketException: {0}!", TraceEventType.Warning, se);
            }
            finally
            {
                e.Dispose();
            }
        }
예제 #14
0
        private void ProduceEnd(ProduceEndType endType)
        {
            Action drained = () =>
            {
                switch (endType)
                {
                case ProduceEndType.SocketShutdownSend:
                    _socket.Shutdown(SocketShutdown.Send);
                    break;
                case ProduceEndType.ConnectionKeepAlive:
                    ThreadPool.QueueUserWorkItem(_ => Go(true, null));
                    break;
                case ProduceEndType.SocketDisconnect:
                    _services.Trace.Event(TraceEventType.Stop, TraceMessage.Connection);

                    _baton.Free();

                    var receiveSocketEvent = Interlocked.Exchange(ref _receiveSocketEvent, null);

                    // this has a race condition
                    if (receiveSocketEvent.Completed == null)
                    {
                        _services.Memory.FreeSocketEvent(receiveSocketEvent);
                    }
                    else
                    {
                        receiveSocketEvent.Completed = () => _services.Memory.FreeSocketEvent(receiveSocketEvent);
                    }

                    _socket.Shutdown(SocketShutdown.Receive);

                    var e = new SocketAsyncEventArgs();
                    Action cleanup = () =>
                    {
                        e.Dispose();
                        _disconnected(_socket);
                    };

                    e.Completed += (_, __) => cleanup();
                    if (!_socket.DisconnectAsync(e))
                    {
                        cleanup();
                    }
                    break;
                }
            };

            if (!_socketSender.Flush(drained))
            {
                drained.Invoke();
            }
        }
예제 #15
0
        void Complete(SocketAsyncEventArgs e, bool completeSynchronously)
        {
            TransportBase transport = null;
            Exception exception = null;
            if (e.SocketError != SocketError.Success)
            {
                exception = new SocketException((int)e.SocketError);
                if (e.AcceptSocket != null)
                {
                    e.AcceptSocket.Dispose();
                }
            }
            else
            {
                try
                {
                    Fx.Assert(e.ConnectSocket != null, "Must have a valid socket accepted.");
                    e.ConnectSocket.NoDelay = true;
                    transport = new TcpTransport(e.ConnectSocket, this.transportSettings);
                    transport.Open();
                }
                catch (Exception exp)
                {
                    if (Fx.IsFatal(exp))
                    {
                        throw;
                    }

                    exception = exp;
                    if (transport != null)
                    {
                        transport.SafeClose();
                    }
                    transport = null;
                }
            }

            e.Dispose();
            this.callbackArgs.CompletedSynchronously = completeSynchronously;
            this.callbackArgs.Exception = exception;
            this.callbackArgs.Transport = transport;

            if (!completeSynchronously)
            {
                this.callbackArgs.CompletedCallback(this.callbackArgs);
            }
        }
예제 #16
0
 private void Succeed()
 {
     OnSucceed();
     _userArgs.FinishWrapperConnectSuccess(_internalArgs.ConnectSocket, _internalArgs.BytesTransferred, _internalArgs.SocketFlags);
     _internalArgs.Dispose();
 }
예제 #17
0
 protected void Succeed()
 {
     OnSucceed();
     userArgs.FinishWrapperConnectSuccess(internalArgs.ConnectSocket, internalArgs.BytesTransferred, internalArgs.SocketFlags);
     internalArgs.Dispose();
 }
예제 #18
0
 private void OnSendCompleted(object sender, SocketAsyncEventArgs socketAsyncEventArgs)
 {
     OnMessageSended((NetworkMessage)socketAsyncEventArgs.UserToken);
     socketAsyncEventArgs.Dispose();
 }
예제 #19
0
        void SocketAsyncEventArgs_Connected(object sender, SocketAsyncEventArgs e)
        {
            if (e.LastOperation == SocketAsyncOperation.Connect)
            {
                if (e.SocketError == SocketError.Success)
                {
            #if Matrix_Diagnostics
                    Monitor.ReportImportant("Socket connected.");
            #endif
                    RaiseConnectedEvent();
                    AssignAsyncReceiveArgs(false);
                }
                else if (e.SocketError == SocketError.IsConnected)
                {// Already connected.
                    // Connect failed.
            #if Matrix_Diagnostics
                    Monitor.ReportImportant("Socket already connected.");
            #endif
                }
                else
                {
            #if Matrix_Diagnostics
                    Monitor.ReportImportant("Socket connection failed: " + e.SocketError.ToString());
            #endif
                }
            }
            else
            {
                // Connect failed.
            #if Matrix_Diagnostics
                Monitor.ReportImportant("Socket async connect failed.");
            #endif
            }

            lock (_syncRoot)
            {
                if (_asyncConnectArgs == e)
                {
                    _asyncConnectArgs.Dispose();
                    _asyncConnectArgs = null;
                }
                else
                {
            #if Matrix_Diagnostics
                    Monitor.Error("SocketAsyncEventArgs mismatch.");
            #endif
                    e.Dispose();
                    _asyncConnectArgs = null;
                }
            }
        }
예제 #20
0
        /// <summary>
        /// release
        /// </summary>
        /// <param name="e"></param>
        public void ReleaseSocketAsyncEventArgs(SocketAsyncEventArgs e)
        {
            if (e.Buffer == null || e.Buffer.Length != this.MessageBufferSize)
            {
                e.Dispose(); return;
            }

            if (this._stack.Count >= 50000) { e.Dispose(); return; }

            this._stack.Push(e);
        }
예제 #21
0
        public void BeginDisconnectCallbackAsync(object sender, SocketAsyncEventArgs e)
        {
            if (Disposed)
                return;

            BaseSocketConnection connection = null;

            try
            {
                connection = (BaseSocketConnection)e.UserToken;

                e.Completed -= new EventHandler<SocketAsyncEventArgs>(BeginDisconnectCallbackAsync);
                e.UserToken = null;
                e.Dispose();
                e = null;

                if (!connection.Active)
                    return;

                lock (connection.Context.SyncActive)
                {
                    CloseConnection(connection);
                    FireOnDisconnected(connection);
                }
            }
            finally
            {
                Console.WriteLine(connection.Context.ConnectionId + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss:fff"));
                DisposeConnection(connection);
                RemoveSocketConnection(connection);
                connection = null;
            }
        }
예제 #22
0
        /// <summary>
        /// Accepts complete event's callback funciton.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void AcceptAsyncCompleted(object sender, SocketAsyncEventArgs e)
        {
            Socket sock = null;
            try
            {
                sock = e.AcceptSocket;
                sock.SendBufferSize = SEND_BUFF_SIZE;

                BaseClient client = GetNewClient();

                //TrieuLSL

                try
                {
                    if (log.IsInfoEnabled)
                    {
                        string ip = sock.Connected ? sock.RemoteEndPoint.ToString() : "socket disconnected";
                        log.Info("Incoming connection from " + ip);
                    }

                    lock (_clients.SyncRoot)
                    {
                        
                        _clients.Add(client, client);//Add the client instance to a hy dictionary.
                        client.Disconnected += client_Disconnected;
                    }

                    client.Connect(sock);
                    client.ReceiveAsync();
                }
                catch (Exception ex)
                {
                    log.ErrorFormat("create client failed:{0}", ex);
                    client.Disconnect();
                }
            }
            catch
            {
                if (sock != null) // don't leave the socket open on exception
                    try { sock.Close(); }
                    catch { }
            }
            finally
            {
                e.Dispose();
                AcceptAsync();
            }
        }
예제 #23
0
        private void EndReceive(object sender, SocketAsyncEventArgs pArguments)
        {
            if (mDisconnected != 0) return;
            if (pArguments.BytesTransferred <= 0)
            {
                Disconnect();
                return;
            }
            mReceiveLength += pArguments.BytesTransferred;

            if (mReceivingPacketLength == mReceiveLength)
            {
                if (mHeader) //parse headers
                {
                    mReceivingPacketLength = BitConverter.ToInt32(mReceiveBuffer, 0);
                    mReceiveLength = 0;
                    mReceiveStart = 0;
                    mHeader = false;
                    // mReceiveBuffer = new byte[mReceivingPacketLength];
                }
                else
                { //parse packets
                    byte[] packetData = new byte[mReceivingPacketLength];
                    Buffer.BlockCopy(mReceiveBuffer, 0, packetData, 0, mReceivingPacketLength);
                    if (!mIVs)
                    {
                        InterPacket packet = new InterPacket(packetData);
                        if (packet.OpCode == InterHeader.IVS)
                        {
                            Log.WriteLine(LogLevel.Info, "IV data received");
                            packet.ReadBytes(mIVRecv);
                            mIVs = true;
                        }
                        else
                        {
                            Log.WriteLine(LogLevel.Info, "Got wrong packet.");
                            Disconnect();
                        }
                    }
                    else
                    {
                        packetData = InterCrypto.DecryptData(mIVRecv, packetData);
                        if (OnPacket != null)
                        {
                            InterPacket packet = new InterPacket(packetData);
                            this.OnPacket(this, new InterPacketReceivedEventArgs(packet, this));
                        }
                    }
                    //we reset this packet
                    mReceivingPacketLength = 4;
                    mReceiveLength = 0;
                    mReceiveStart = 0;
                    mHeader = true;
                    // mReceiveBuffer = new byte[4];
                }
            }
            else
            {
                mReceiveStart += mReceivingPacketLength;
            }

            BeginReceive();
            pArguments.Dispose();
        }
예제 #24
0
        private void ConnectCompleted(object sender, SocketAsyncEventArgs e)
        {
            try
            {
                if (e.SocketError != SocketError.Success)
                {
                    HandleSocketError(e.SocketError);
                    return;
                }

                Debug.Assert(e.UserToken != null);
                var token = (Tuple<bool, string, IrcRegistrationInfo>)e.UserToken;

                // Create stream for received data. Use SSL stream on top of network stream, if specified.
                this.receiveStream = new CircularBufferStream(socketReceiveBufferSize);
            #if SILVERLIGHT
                this.dataStream = this.receiveStream;
            #else
                this.dataStream = GetDataStream(token.Item1, token.Item2);
            #endif
                this.dataStreamReader = new StreamReader(this.dataStream, TextEncoding);
                this.dataStreamLineReader = new SafeLineReader(this.dataStreamReader);

                // Start sending and receiving data to/from server.
                this.sendTimer.Change(0, Timeout.Infinite);
                ReceiveAsync();

                HandleClientConnected(token.Item3);
            }
            catch (SocketException exSocket)
            {
                HandleSocketError(exSocket);
            }
            catch (ObjectDisposedException)
            {
                // Ignore.
            }
            #if !DEBUG
            catch (Exception ex)
            {
                OnConnectFailed(new IrcErrorEventArgs(ex));
            }
            #endif
            finally
            {
                e.Dispose();
            }
        }
예제 #25
0
        private void ReceiveCompleted(object sender, SocketAsyncEventArgs e)
        {
            try
            {
                if (e.SocketError != SocketError.Success)
                {
                    HandleSocketError(e.SocketError);
                    return;
                }

                // Check if remote host has closed connection.
                if (e.BytesTransferred == 0)
                {
                    HandleClientDisconnected();
                    return;
                }

                // Indicate that block of data has been read into receive buffer.
                this.receiveStream.WritePosition += e.BytesTransferred;
                this.dataStreamReader.DiscardBufferedData();

                // Read each terminated line of characters from data stream.
                while (true)
                {
                    // Read next line from data stream.
                    var line = this.dataStreamLineReader.ReadLine();
                    if (line == null)
                        break;
                    if (line.Length == 0)
                        continue;

                    string prefix = null;
                    string lineAfterPrefix = null;

                    // Extract prefix from message line, if it contains one.
                    if (line[0] == ':')
                    {
                        var firstSpaceIndex = line.IndexOf(' ');
                        Debug.Assert(firstSpaceIndex != -1);
                        prefix = line.Substring(1, firstSpaceIndex - 1);
                        lineAfterPrefix = line.Substring(firstSpaceIndex + 1);
                    }
                    else
                    {
                        lineAfterPrefix = line;
                    }

                    // Extract command from message.
                    var command = lineAfterPrefix.Substring(0, lineAfterPrefix.IndexOf(' '));
                    var paramsLine = lineAfterPrefix.Substring(command.Length + 1);

                    // Extract parameters from message.
                    // Each parameter is separated by single space, except last one, which may contain spaces if it
                    // is prefixed by colon.
                    var parameters = new string[maxParamsCount];
                    int paramStartIndex, paramEndIndex = -1;
                    int lineColonIndex = paramsLine.IndexOf(" :");
                    if (lineColonIndex == -1 && !paramsLine.StartsWith(":"))
                        lineColonIndex = paramsLine.Length;
                    for (int i = 0; i < parameters.Length; i++)
                    {
                        paramStartIndex = paramEndIndex + 1;
                        paramEndIndex = paramsLine.IndexOf(' ', paramStartIndex);
                        if (paramEndIndex == -1)
                            paramEndIndex = paramsLine.Length;
                        if (paramEndIndex > lineColonIndex)
                        {
                            paramStartIndex++;
                            paramEndIndex = paramsLine.Length;
                        }
                        parameters[i] = paramsLine.Substring(paramStartIndex, paramEndIndex - paramStartIndex);
                        if (paramEndIndex == paramsLine.Length)
                            break;
                    }

                    // Parse received IRC message.
                    var message = new IrcMessage(this, prefix, command, parameters);
                    var messageReceivedEventArgs = new IrcRawMessageEventArgs(message, line);
                    OnRawMessageReceived(messageReceivedEventArgs);
                    ReadMessage(message, line);

            #if DEBUG
                    DebugUtilities.WriteIrcRawLine(this, ">>> " + messageReceivedEventArgs.RawContent);
            #endif
                }

                // Continue reading data from socket.
                ReceiveAsync();
            }
            catch (SocketException exSocket)
            {
                HandleSocketError(exSocket);
            }
            catch (ObjectDisposedException)
            {
                // Ignore.
            }
            #if !DEBUG
            catch (Exception ex)
            {
                OnError(new IrcErrorEventArgs(ex));
            }
            #endif
            finally
            {
                e.Dispose();
            }
        }
예제 #26
0
        private void ReceiveCompleted(object sender, SocketAsyncEventArgs e)
        {
            try
            {
                if (e.SocketError != SocketError.Success)
                {
                    HandleSocketError(e.SocketError);
                    return;
                }

                // Check if remote host has closed connection.
                if (e.BytesTransferred == 0)
                {
                    Disconnect();
                    return;
                }

                // Indicate that block of data has been read into receive buffer.
                this.receiveStream.WritePosition += e.BytesTransferred;
                this.dataStreamReader.DiscardBufferedData();

                // Read each terminated line of characters from data stream.
                while (true)
                {
                    // Read next line from data stream.
                    var line = this.dataStreamLineReader.ReadLine();
                    if (line == null)
                        break;
                    if (line.Length == 0)
                        continue;

                    ParseMessage(line);
                }

                // Continue reading data from socket.
                ReceiveAsync();
            }
            catch (SocketException exSocket)
            {
                HandleSocketError(exSocket);
            }
            catch (ObjectDisposedException)
            {
                // Ignore.
            }
            #if !DEBUG
            catch (Exception ex)
            {
                OnError(new IrcErrorEventArgs(ex));
            }
            #endif
            finally
            {
                e.Dispose();
            }
        }
예제 #27
0
        private void DisconnectCompleted(object sender, SocketAsyncEventArgs e)
        {
            try
            {
                if (e.SocketError != SocketError.Success)
                {
                    HandleSocketError(e.SocketError);
                    return;
                }

                HandleClientDisconnected();
            }
            catch (SocketException exSocket)
            {
                HandleSocketError(exSocket);
            }
            catch (ObjectDisposedException)
            {
                // Ignore.
            }
            #if !DEBUG
            catch (Exception ex)
            {
                OnError(new IrcErrorEventArgs(ex));
            }
            #endif
            finally
            {
                e.Dispose();
            }
        }
예제 #28
0
        /// <summary>
        /// Connect callback!
        /// </summary>
        /// <param name="ar"></param>
        internal void BeginConnectCallbackAsync(object sender, SocketAsyncEventArgs e)
        {
            if (!Disposed)
            {
                BaseSocketConnection connection = null;
                SocketConnector connector = null;
                Exception exception = null;

                if (e.SocketError == SocketError.Success)
                {
                    try
                    {
                        connector = (SocketConnector)e.UserToken;

                        connection = new ClientSocketConnection(Context.Host, connector, connector.Socket);

                        //----- Adjust buffer size!
                        connector.Socket.ReceiveBufferSize = Context.Host.Context.SocketBufferSize;
                        connector.Socket.SendBufferSize = Context.Host.Context.SocketBufferSize; ;

                        //----- Initialize!
                        Context.Host.AddSocketConnection(connection);
                        connection.Active = true;

                        Context.Host.InitializeConnection(connection);
                    }
                    catch (Exception ex)
                    {
                        exception = ex;

                        if (connection != null)
                        {
                            Context.Host.DisposeConnection(connection);
                            Context.Host.RemoveSocketConnection(connection);

                            connection = null;
                        }
                    }
                }
                else
                {
                    exception = new SocketException((int)e.SocketError);
                }

                if (exception != null)
                {
                    FReconnectAttempted++;
                    ReconnectConnection(false, exception);
                }
            }

            e.UserToken = null;
            e.Dispose();
            e = null;
        }
예제 #29
0
        private void SendCompleted(object sender, SocketAsyncEventArgs e)
        {
            try
            {
                if (e.SocketError != SocketError.Success)
                {
                    HandleSocketError(e.SocketError);
                    return;
                }

                // Handle sent IRC message.
                Debug.Assert(e.UserToken != null);
                var messageSentEventArgs = (IrcRawMessageEventArgs)e.UserToken;
                OnRawMessageSent(messageSentEventArgs);

            #if DEBUG
                DebugUtilities.WriteIrcRawLine(this, "<<< " + messageSentEventArgs.RawContent);
            #endif
            }
            catch (ObjectDisposedException)
            {
                // Ignore.
            }
            #if !DEBUG
            catch (Exception ex)
            {
                OnError(new IrcErrorEventArgs(ex));
            }
            #endif
            finally
            {
                e.Dispose();
            }
        }
        protected void ProcessConnect(Socket socket, object state, SocketAsyncEventArgs e)
        {
            if (e != null && e.SocketError != SocketError.Success)
            {
                e.Dispose();
                m_InConnecting = false;
                OnError(new SocketException((int)e.SocketError));
                return;
            }

            if (socket == null)
            {
                m_InConnecting = false;
                OnError(new SocketException((int)SocketError.ConnectionAborted));
                return;
            }

            //To walk around a MonoTouch's issue
            //one user reported in some cases the e.SocketError = SocketError.Succes but the socket is not connected in MonoTouch
            if (!socket.Connected)
            {
                m_InConnecting = false;
#if SILVERLIGHT || NETFX_CORE
                var socketError = SocketError.ConnectionReset;
#else
                var socketError = (SocketError)socket.GetSocketOption(SocketOptionLevel.Socket, SocketOptionName.Error);
#endif
                OnError(new SocketException((int)socketError));
                return;
            }

            if (e == null)
                e = new SocketAsyncEventArgs();

            e.Completed += SocketEventArgsCompleted;

            Client = socket;

            m_InConnecting = false;

#if !SILVERLIGHT && !NETFX_CORE
            try
            {
                //Set keep alive
                Client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.KeepAlive, true);
            }
            catch
            {
            }
            
#endif
            OnGetSocket(e);
        }
예제 #31
0
        private void EndReceive(object sender, SocketAsyncEventArgs pArguments)
        {
            if (mDisconnected != 0) return;
            if (pArguments.BytesTransferred <= 0)
            {
                Disconnect();
                return;
            }
            mReceiveLength += pArguments.BytesTransferred;

            while (mReceiveLength > 1)
            {
                //parse headers
                //TODO: proper rewrite!
                if (mReceivingPacketLength == 0)
                {
                    mReceivingPacketLength = receiveBuffer[mReceiveStart];
                    if (mReceivingPacketLength == 0)
                    {
                        if (mReceiveLength >= 3)
                        {
                            mReceivingPacketLength = BitConverter.ToUInt16(receiveBuffer, mReceiveStart + 1);
                            headerLength = 3;
                        }
                        else
                        {
                            break;
                        }
                    }
                    else
                    {
                        headerLength = 1;
                    }
                }

                //parse packets
                if (mReceivingPacketLength > 0 && mReceiveLength >= mReceivingPacketLength + headerLength)
                {
                    byte[] packetData = new byte[mReceivingPacketLength];
                    Buffer.BlockCopy(receiveBuffer, mReceiveStart + headerLength, packetData, 0, mReceivingPacketLength);
                    crypto.Crypt(packetData, 0, mReceivingPacketLength);
                    if (OnPacket != null)
                    {
                        Packet packet = new Packet(packetData);
                        if (packet.Header > 49)
                        {
                            Log.WriteLine(LogLevel.Warn, "Header out of range from {0} ({1}|{2})", Host, packet.Header, packet.Type);
                            Disconnect();
                        }
                        else
                        {
                            this.OnPacket(this, new PacketReceivedEventArgs(packet));
                        }
                    }

                    //we reset this packet
                    mReceiveStart += mReceivingPacketLength + headerLength;
                    mReceiveLength -= mReceivingPacketLength + headerLength;
                    mReceivingPacketLength = 0;
                }
                else break;
            }

            if (mReceiveLength == 0) mReceiveStart = 0;
            else if (mReceiveStart > 0 && (mReceiveStart + mReceiveLength) >= receiveBuffer.Length)
            {
                Buffer.BlockCopy(receiveBuffer, mReceiveStart, receiveBuffer, 0, mReceiveLength);
                mReceiveStart = 0;
            }
            if (mReceiveLength == receiveBuffer.Length)
            {
                Disconnect();
            }
            else BeginReceive();
            pArguments.Dispose();
        }
예제 #32
0
        bool HandleAcceptComplete(SocketAsyncEventArgs e, bool completedSynchronously)
        {
            if (e.SocketError == SocketError.Success)
            {
                TcpTransport transport = new TcpTransport(e.AcceptSocket, this.transportSettings);
                transport.Open();

                TransportAsyncCallbackArgs args = new TransportAsyncCallbackArgs();
                args.Transport = transport;
                args.CompletedSynchronously = completedSynchronously;
                this.OnTransportAccepted(args);
                return true;
            }
            else
            {
                e.Dispose();
                this.TryClose(new SocketException((int)e.SocketError));
                return false;
            }
        }
예제 #33
0
파일: Client.cs 프로젝트: wilson0x4d/Mubox
        private void SendCommand(string commandName, EventHandler<SocketAsyncEventArgs> callback, params string[] args)
        {
            if (commandName == null)
            {
                return;
            }
            DateTime sendCommandStartTime = DateTime.Now;
            StringBuilder format = new StringBuilder("|" + Encode(commandName));

            if ((args != null) && (args.Length > 0))
            {
                for (int i = 0; i < args.Length; i++)
                {
                    format.AppendFormat("/{0}", Encode(args[i]));
                }
            }
            format.Append("/?");

            byte[] message = ASCIIEncoding.ASCII.GetBytes(format.ToString());

            SocketAsyncEventArgs socketAsyncEventArgs = new SocketAsyncEventArgs();
            socketAsyncEventArgs.SetBuffer(message, 0, message.Length);
            socketAsyncEventArgs.Completed += (sender, e) =>
                {
                    try
                    {
                        sendCommandTimeSpent = (DateTime.Now - sendCommandStartTime);
                        if (callback != null)
                        {
                            callback(sender, e);
                        }
                    }
                    catch (Exception)
                    {
                        // TODO: log
                        if (socketAsyncEventArgs != null)
                        {
                            socketAsyncEventArgs.Dispose();
                        }
                    }
                };
            if ((this.EndPoint == null) || (this.EndPoint.Client == null))
            {
                return;
            }
            if (this.EndPoint.Client.SendAsync(socketAsyncEventArgs))
            {
                sendCommandTimeSpent = (DateTime.Now - sendCommandStartTime);
                if (callback != null)
                {
                    callback(this, socketAsyncEventArgs);
                }
            }
            ClientTxPerformanceIncrement(commandName);
        }
예제 #34
0
        public void Send(NetworkMessage message)
        {
            lock (this)
            {
                if (!IsConnected)
                    return;

                var args = new SocketAsyncEventArgs();
                args.Completed += OnSendCompleted;
                args.UserToken = message;

                byte[] data;
                using (var writer = new BigEndianWriter())
                {
                    message.Pack(writer);
                    data = writer.Data;
                }

                args.SetBuffer(data, 0, data.Length);

                if (!Socket.SendAsync(args))
                {
                    OnMessageSended(message);
                    args.Dispose();
                }

                LastActivity = DateTime.Now;
            }
        }