示例#1
0
        /// <summary>
        /// Sends data to the underlying connection if it is connected.
        /// NOTE: Will NOT connect the underlying socket if it is not connected already.
        /// </summary>
        /// <param name="data">Data to be sent.</param>
        public void Send(byte[] data)
        {
            if (data == null)
            {
                throw new ArgumentNullException("data");
            }

            if (IsConnected)
            {
                // Pull down a SocketAsyncEventArg to send with
                var sendAsyncEventArgs = transmitPool.Pull();
                sendAsyncEventArgs.RemoteEndPoint = RemoteEndPoint;

                if (sendAsyncEventArgs.LastOperation == SocketAsyncOperation.None)
                {
                    sendAsyncEventArgs.Completed += new EventHandler <SocketAsyncEventArgs>(AsyncEventCompleted);
                }

                // Set our buffer
                sendAsyncEventArgs.SetBuffer(data, 0, data.Length);

                // Did the operation complete synchroously?
                if (!underlyingSocket.SendAsync(sendAsyncEventArgs))
                {
                    AsyncEventCompleted(this, sendAsyncEventArgs);
                }
            }
        }
示例#2
0
        /// <summary>
        /// Connects the underlying connection if it is not already connected.
        /// </summary>
        public void Connect()
        {
            // Ensure exclusivity to the resource, we only want one connection attempt.
            connectingResetEvent.WaitOne();

            if (!IsConnected)
            {
                // Make a new instance of Socket, in Silverlight there is no DisconnectAsync on Sockets.
                underlyingSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

                // Pull down a SocketAsyncEventArg to connect with.
                var connectAsyncEventArgs = connectionPool.Pull();
                connectAsyncEventArgs.RemoteEndPoint = RemoteEndPoint;

                if (connectAsyncEventArgs.LastOperation == SocketAsyncOperation.None)
                {
                    connectAsyncEventArgs.Completed += new EventHandler <SocketAsyncEventArgs>(AsyncEventCompleted);
                }

                // Did the operation complete synchronously?
                if (!underlyingSocket.ConnectAsync(connectAsyncEventArgs))
                {
                    AsyncEventCompleted(this, connectAsyncEventArgs);
                }

                connectingVerifyResetEvent.WaitOne();
            }
        }