SendAsync() public method

public SendAsync ( SocketAsyncEventArgs e ) : bool
e SocketAsyncEventArgs
return bool
示例#1
0
        /// <summary>
        /// 批量发送
        /// </summary>
        public void Send(IList <ArraySegment <byte> > content)
        {
            if (_tcpSock != null && _tcpSock.Connected)
            {
                SocketAsyncEventArgs args = SocketHelpers.AcquireSocketArg();
                if (args != null)
                {
                    args.Completed += SendAsyncComplete;
                    args.BufferList = content;
                    args.UserToken  = this;
                    _tcpSock.SendAsync(args);

                    //unchecked
                    //{
                    //    _bytesSent += (uint)length;
                    //}

                    //Interlocked.Add(ref _totalBytesSent, length);
                }
                else
                {
                    Csl.Wl(string.Format("Client {0}'s SocketArgs are null", this));
                }
            }
        }
示例#2
0
 // 发送消息头
 private void SendMessageHeader()
 {
     ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////// - LOCK ( SpinLock )
     // Lock objects : SendMessageQueue
     LOCK(ref SendMessageQueueLockRoot);
     try {
         if (SendMessageQueue.Count == 0)
         {
             // 消息全部发送完毕, 重置发送状态
             Sending = false;
             return;
         }
         SendingMessage = SendMessageQueue[0];
         SendMessageQueue.RemoveAt(0);
     } finally { UNLOCK(ref SendMessageQueueLockRoot); }
     ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////// - UNLOCK ( SpinLock )
     // 计算剩余发送步骤数
     RemainingSendSteps = SendingMessage.Length == 0 ? 0 : SendingMessage.Buffers.Count;
     Array.Copy(BitConverter.GetBytes(SendingMessage.Info.InternalProtocol), 0, SendingMessageHeader, 0, 2);
     Array.Copy(BitConverter.GetBytes(SendingMessage.Length), 0, SendingMessageHeader, 2, 4);
     SendArgs.SetBuffer(SendingMessageHeader, 0, 6);
     try {
         if (!InnerSocket.SendAsync(SendArgs))
         {
             SendMessageBody();
         }
     } catch { Disconnect(); }
 }
示例#3
0
        internal void SendMessage(string message, bool noWait = false)
        {
            if (isConnected)
            {
                sendWait.Reset();
                Byte[] bytes = Encoding.UTF8.GetBytes(message);

                SocketAsyncEventArgs args = new SocketAsyncEventArgs();
                args.SetBuffer(bytes, 0, bytes.Length);
                args.RemoteEndPoint = endPoint;

                if (noWait)
                {
                    socket.SendAsync(args);
                }
                else
                {
                    args.Completed += OnSend;
                    socket.SendAsync(args);

                    sendWait.WaitOne();
                }
            }
            else
            {
                throw new SocketException(Convert.ToInt32(SocketError.NotConnected));
            }
        }
示例#4
0
        async Task SendAsync(ReadOnlySequence <byte> buffer)
        {
            if (buffer.IsEmpty)
            {
                return;
            }

            if (buffer.IsSingleSegment)
            {
                await socket.SendAsync(MemoryMarshal.AsMemory(buffer.First), SocketFlags.None);
            }
            else
            {
                var list = new List <ArraySegment <byte> >();

                foreach (var memory in buffer)
                {
                    if (MemoryMarshal.TryGetArray(memory, out var segment))
                    {
                        list.Add(segment);
                    }
                    else
                    {
                        throw new Exception("BOOM!");
                    }
                }

                await socket.SendAsync(list, SocketFlags.None);
            }
        }
        public void send_networkMessage(NetworkMsg msg, System.Net.Sockets.Socket socket)
        {
            SocketAsyncEventArgs sendEventArgs = new SocketAsyncEventArgs();//  m_sendEventArgsPool.pop();

            sendEventArgs.Completed += io_completed;
            sendEventArgs.UserToken  = new AsyncUserToken();
            //if (sendEventArgs != null)
            {
                ((AsyncUserToken)sendEventArgs.UserToken).Socket = socket;
                byte[] data   = PBSerializer.serialize(msg);
                byte[] length = new byte[4];
                length = BitConverter.GetBytes(data.Length);
                int    dataLength = BitConverter.ToInt32(length);
                byte[] packedData = new byte[4 + data.Length];
                Buffer.BlockCopy(length, 0, packedData, 0, 4);
                Buffer.BlockCopy(data, 0, packedData, 4, data.Length);
                sendEventArgs.SetBuffer(packedData, 0, packedData.Length);
                socket.SendAsync(sendEventArgs);
            }
            //else
            //{
            //    m_waitSendEvent.WaitOne();
            //    send_networkMessage(msg, socket);
            //}
        }
        public IObservable<Unit> SendMessage(Socket connectedSocket, SocketAsyncEventArgs socketEventArgs, IScheduler scheduler, string message)
        {
            if (connectedSocket == null)
                throw new ArgumentNullException("connectedSocket");

            if (socketEventArgs == null)
                throw new ArgumentNullException("socketEventArgs");

            return Observable.Create<Unit>(observer =>
            {
                var disposable = new CompositeDisposable();
                var buffer = Encoding.UTF8.GetBytes(message);

                var disposableCompletedSubscription = socketEventArgs.CompletedObservable().ObserveOn(scheduler).Subscribe(_ =>
                {
                    SendNotificationToObserver(observer, socketEventArgs);
                });

                var disposableActions = scheduler.Schedule(() =>
                {
                    socketEventArgs.SetBuffer(buffer, 0, buffer.Length);
                    if (!connectedSocket.SendAsync(socketEventArgs))
                    {
                        SendNotificationToObserver(observer, socketEventArgs);
                    }
                });

                disposable.Add(disposableCompletedSubscription);
                disposable.Add(disposableActions);

                return disposable;
            });
        }
示例#7
0
        public sealed override async Task <SocketError> SendAsync(Memory <byte> data)
        {
            // Write the locally buffered data to the network.
            try
            {
                if (_socket != null)
                {
                    var result = await _socket.SendAsync(new ArraySegment <byte>(data.ToArray()), SocketFlags.None).ConfigureAwait(false);

                    if (result != data.Length)
                    {
                        return(SocketError.Fault);
                    }
                }
                else
                {
                    return(SocketError.Fault);
                }
            }
            catch (Exception)
            {
                //TODO
                // If this is an unknown status it means that the error if fatal and retry will likely fail.
                //if (SocketError.GetStatus(exception.HResult) == SocketErrorStatus.Unknown)
                //{
                //    throw;
                //}
                return(SocketError.Fault);
            }
            return(SocketError.Success);
        }
        public void AsyncTo(System.Net.Sockets.Socket socket, object userToken, int length)
        {
            this.IsReceive = false;
            this.UserToken = userToken;
            this.SetBuffer(BufferX.Memory.Slice(0, length));
            var lastSocket = LastSocket;

            LastSocket = socket;
            if (!socket.SendAsync(this))
            {
                if (lastSocket == socket)
                {
                    LoopCount++;
                }
                else
                {
                    LoopCount = 0;
                }
                if (LoopCount > 50)
                {
                    LoopCount = 0;
                    Task.Run(() => { this.InvokeCompleted(); });
                }
                else
                {
                    this.InvokeCompleted();
                }
            }
            else
            {
                LastSocket = null;
                LoopCount  = 0;
            }
        }
示例#9
0
        /// <summary>
        /// 异步的发送数据
        /// </summary>
        /// <param name="e"></param>
        /// <param name="data"></param>
        public int AsyncSend(SocketAsyncEventArgs e, byte[] data)
        {
            try
            {
                if (e.SocketError == SocketError.Success)
                {
                    System.Net.Sockets.Socket s = e.AcceptSocket;//和客户端关联的socket
                    if (s.Connected)
                    {
                        Array.Copy(data, 0, e.Buffer, 0, data.Length);//设置发送数据

                        //e.SetBuffer(data, 0, data.Length); //设置发送数据
                        if (!s.SendAsync(e))//投递发送请求,这个函数有可能同步发送出去,这时返回false,并且不会引发SocketAsyncEventArgs.Completed事件
                        {
                            // 同步发送时处理发送完成事件
                            ProcessSend(e);
                        }
                        else
                        {
                            CloseClientSocket(e);
                        }
                    }
                }
                else
                {
                    return(-1);
                }
            }
            catch (Exception ex)
            {
                return(-1);
            }

            return(0);
        }
示例#10
0
        public virtual int Send(byte[] bData, int nLength, bool bTransform)
        {
            if (this.m_bSocketClientDisposed == true)
            {
                return(-1);
            }

            int nRet = -1;

            lock (SyncRoot)
            {
                if (Client != null && Client.Connected)
                {
                    try
                    {
                        if (bTransform == true)
                        {
                            bData = TransformSendData(bData);
                        }

                        if ((bData == null) || (bData.Length <= 0))
                        {
                            return(0);
                        }

                        SocketAsyncEventArgs sendargs = new SocketAsyncEventArgs();
                        sendargs.SetBuffer(bData, 0, bData.Length);
                        sendargs.Completed += new EventHandler <SocketAsyncEventArgs>(sendargs_Completed);

                        Client.SendAsync(sendargs);
                    }
                    catch (System.Net.Sockets.SocketException ex)
                    {
                        if (m_Logger != null)
                        {
                            m_Logger.LogError(ToString(), MessageImportance.Highest, ex.ToString());
                        }

                        OnDisconnect("Send failed");
                        throw new Exception("Send Failed", ex);
                    }
                    catch (System.Exception ex2)
                    {
                        if (m_Logger != null)
                        {
                            m_Logger.LogError(ToString(), MessageImportance.Highest, ex2.ToString());
                        }

                        OnDisconnect(ex2.ToString());
                        throw new Exception("Send Failed", ex2);
                    }
                }
                else
                {
                    OnDisconnect("Client not connected");
                }
            }
            return(nRet);
        }
示例#11
0
 private void SendCompleted(object sender, System.Net.Sockets.SocketAsyncEventArgs e)
 {
     if (e.SocketError == SocketError.Success && e.BytesTransferred > 0)
     {
         if (e.BytesTransferred < e.Count)
         {
             e.SetBuffer(e.Offset + e.BytesTransferred, e.Count - e.BytesTransferred);
             if (!mSocket.SendAsync(e))
             {
                 SendCompleted(this, e);
             }
         }
     }
     else
     {
         ReleaseSocket();
     }
 }
示例#12
0
    public void SendAsync(byte[] buf)
    {
        int length = Math.Min(sendBuf.Length, buf.Length);

        Buffer.BlockCopy(buf, 0, sendBuf, 0, length);

        if (!socket.SendAsync(sendArgs))
        {
            ProcessSend(sendArgs);
        }
    }
示例#13
0
        public bool SendAsync(byte[] buffer, SendCallbackDelegate callback)
        {
            SocketAsyncEventArgs sendArgs = new SocketAsyncEventArgs();

            sendArgs.SetBuffer(buffer, 0, buffer.Length);
            sendArgs.Completed += new EventHandler <SocketAsyncEventArgs>((o, e) =>
            {
                callback(e.SocketError, e.BytesTransferred);
            });

            return(_socket.SendAsync(sendArgs));
        }
示例#14
0
		partial void SendTimeRequest()
		{
			try
			{
				byte[] buffer = new byte[48];
				buffer[0] = 0x1B;

				DnsEndPoint _endPoint = new DnsEndPoint(_ServerAddress, 123, AddressFamily.InterNetwork);
				Socket socket = null;
				var socketArgs = new SocketAsyncEventArgs() { RemoteEndPoint = _endPoint };
				try
				{
					socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);

					try
					{
						socketArgs.Completed += Socket_Completed_SendAgain;
						//TFW - For some reason 'ConnectAsync' reports an error
						//desktop .Net 4, but 'Connect' works fine. On WP
						//only ConnectAsync is available, and it appears to work.
#if USE_CONNECTASYNC
					socketArgs.SetBuffer(buffer, 0, buffer.Length);
					if (!socket.ConnectAsync(socketArgs))
						Socket_Completed_SendAgain(socket, socketArgs);
#else
						socket.Connect(socketArgs.RemoteEndPoint);
						socketArgs.SetBuffer(buffer, 0, buffer.Length);
						if (!socket.SendAsync(socketArgs))
							Socket_Completed_SendAgain(socket, socketArgs);
#endif
					}
					catch
					{
						socketArgs.Completed -= this.Socket_Completed_SendAgain;
						throw;
					}
				}
				catch
				{
					socket?.Dispose();
					throw;
				}
			}
			catch (SocketException se)
			{
				OnErrorOccurred(new NtpNetworkException(se.Message, (int)se.SocketErrorCode, se));
			}
			catch (Exception ex)
			{
				OnErrorOccurred(new NtpNetworkException(ex.Message, -1, ex));
			}
		}
示例#15
0
        /// <summary>
        /// 输出错误状态
        /// </summary>
        /// <param name="state">错误状态</param>
        internal void ResponseError(ResponseState state)
        {
            if (DomainServer != null)
            {
                Response response = DomainServer.GetErrorResponseData(state, Header.IsGZip);
                if (response != null)
                {
                    if (state != ResponseState.NotFound404 || Header.Method != MethodType.GET)
                    {
                        Header.Flag &= HeaderFlag.All ^ HeaderFlag.IsKeepAlive;
                    }
                    if (responseHeader(ref response)) return;
                }
            }
            byte[] data = errorResponseDatas[(int)state];
            System.Net.Sockets.Socket socket = Socket;
            if (data != null && socket != null)
            {
                try
                {
                    SendType = state == ResponseState.NotFound404 && Header.Method == MethodType.GET ? SendType.Next : SendType.Close;
                    Data.Set(data, 0, data.Length);
                    Timeout = Config.GetTimeout(Data.Length);
#if DOTNET2
                    SocketError socketError;
                    IAsyncResult async = socket.BeginSend(data, 0, Data.Length, SocketFlags.None, out socketError, onSendAsyncCallback, socket);
                    if (socketError == SocketError.Success)
                    {
                        if (!async.CompletedSynchronously) Http.Header.ReceiveTimeout.Push(this, socket);
                        return;
                    }
#else
                    sendAsyncLock.EnterSleepFlag();
                    sendAsyncEventArgs.SetBuffer(data, 0, Data.Length);
                    if (socket.SendAsync(sendAsyncEventArgs))
                    {
                        sendAsyncLock.SleepFlag = 0;
                        Http.Header.ReceiveTimeout.Push(this, socket);
                        sendAsyncLock.Exit();
                        return;
                    }
                    sendAsyncLock.ExitSleepFlag();
                    if (onSend()) return;
#endif
                }
                catch (Exception error)
                {
                    Server.RegisterServer.TcpServer.Log.Exception(error, null, LogLevel.Exception | LogLevel.AutoCSer);
                }
            }
            HeaderError();
        }
示例#16
0
        public void AsyncTo(System.Net.Sockets.Socket socket, object userToken, int length)
        {
            this.IsReceive = false;
            this.UserToken = userToken;
#if (NETSTANDARD2_0)
            this.SetBuffer(BufferX.Data, 0, length);
#else
            this.SetBuffer(BufferX.Memory.Slice(0, length));
#endif
            var lastSocket = LastSocket;
            LastSocket = socket;

            /*https://docs.microsoft.com/zh-cn/dotnet/api/system.net.sockets.socket.sendasync?view=netframework-4.7.2
             * public bool SendAsync (System.Net.Sockets.SocketAsyncEventArgs e);
             * 参数
             * e
             * SocketAsyncEventArgs
             * 要用于此异步套接字操作的 SocketAsyncEventArgs 对象。
             * 返回
             * Boolean
             * 如果 I/O 操作挂起,则为 true。 操作完成时,将引发 e 参数的 Completed 事件。
             *
             * 如果 I/O 操作同步完成,则为 false。 在这种情况下,将不会引发 e 参数的 Completed 事件,
             * 并且可能在方法调用返回后立即检查作为参数传递的 e 对象以检索操作的结果。
             */
            if (!socket.SendAsync(this))
            {
                if (lastSocket == socket)
                {
                    LoopCount++;
                }
                else
                {
                    LoopCount = 0;
                }
                if (LoopCount > 50)
                {
                    LoopCount = 0;
                    Task.Run(() => { this.InvokeCompleted(); });
                }
                else
                {
                    this.InvokeCompleted();
                }
            }
            else
            {
                LastSocket = null;
                LoopCount  = 0;
            }
        }
示例#17
0
        ///// <summary>
        ///// 获取请求表单数据[TRY+1]
        ///// </summary>
        ///// <param name="identity">HTTP操作标识</param>
        ///// <param name="page">WEB 页面</param>
        ///// <param name="type">获取请求表单数据回调类型</param>
        ///// <returns>是否匹配会话标识</returns>
        //internal override bool GetForm(long identity, AutoCSer.WebView.Page page, GetFormType type)
        //{
        //    if (Interlocked.CompareExchange(ref this.Identity, identity + 1, identity) == identity)
        //    {
        //        GetFormPage = page;
        //        GetFormType = type;
        //        tryGetForm();
        //        return true;
        //    }
        //    return false;
        //}
        /// <summary>
        /// 获取请求表单数据
        /// </summary>
        /// <param name="page">WEB 页面</param>
        /// <param name="type">获取请求表单数据回调类型</param>
        internal override void GetForm(AutoCSer.WebView.Page page, GetFormType type)
        {
            ++this.Identity;
            GetFormPage = page;
            GetFormType = type;

            Flag |= SocketFlag.GetForm | SocketFlag.IsLoadForm;
            try
            {
                if (Header.Is100Continue == 0)
                {
                    if (getForm()) return;
                }
                else
                {
                    System.Net.Sockets.Socket socket = Socket;
                    if (socket != null)
                    {
                        SendType = SendType.GetForm;
                        Data.Set(continue100, 0, continue100.Length);
                        Timeout = Config.GetTimeout(Data.Length);
#if DOTNET2
                            SocketError socketError;
                            IAsyncResult async = socket.BeginSend(continue100, 0, Data.Length, SocketFlags.None, out socketError, onSendAsyncCallback, socket);
                            if (socketError == SocketError.Success)
                            {
                                if (!async.CompletedSynchronously) Http.Header.ReceiveTimeout.Push(this, socket);
                                return;
                            }
#else
                        sendAsyncLock.EnterSleepFlag();
                        sendAsyncEventArgs.SetBuffer(continue100, 0, Data.Length);
                        if (socket.SendAsync(sendAsyncEventArgs))
                        {
                            sendAsyncLock.SleepFlag = 0;
                            Http.Header.ReceiveTimeout.Push(this, socket);
                            sendAsyncLock.Exit();
                            return;
                        }
                        sendAsyncLock.ExitSleepFlag();
                        if (sendAsyncEventArgs.SocketError == SocketError.Success && sendAsyncEventArgs.BytesTransferred == Data.Length && getForm()) return;
#endif
                    }
                }
            }
            catch (Exception error)
            {
                Server.RegisterServer.TcpServer.Log.Exception(error, null, LogLevel.Exception | LogLevel.AutoCSer);
            }
            HeaderError();
        }
示例#18
0
文件: Socket.cs 项目: spotnet/fusenet
        private bool InternalSend(Stream bData)
		{
			try
			{
                iSend = new System.Net.Sockets.SocketAsyncEventArgs();
                iSend.Completed += new EventHandler<SocketAsyncEventArgs>(iSend_Completed);

                byte[] bD = Common.GetBytes(bData);
				iSend.SetBuffer(bD, 0, bD.Length);

				if (!ClientSocket.SendAsync(iSend)) { iSend_Completed(null, iSend); }
                return true;

			}
            catch (Exception ex) { Close(970, "Send: " + ex.Message); return false; }
		}
示例#19
0
 public void SendMessage(Socket socket, string message)
 {
     socketEventArgs = new SocketAsyncEventArgs();
     socketEventArgs.RemoteEndPoint = socket.RemoteEndPoint;
     socketEventArgs.UserToken = null;
     socketEventArgs.Completed += new EventHandler<SocketAsyncEventArgs>(
         delegate(object sender, SocketAsyncEventArgs e)
         {
             clientDone.Set();
         });
     byte[] byteMessage = Encoding.UTF8.GetBytes(message);
     socketEventArgs.SetBuffer(byteMessage, 0, byteMessage.Length);
     clientDone.Reset();
     socket.SendAsync(socketEventArgs);
     clientDone.WaitOne();
 }
示例#20
0
        static void Main()
        {
            Socket client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            IPEndPoint ipep = new IPEndPoint(IPAddress.Loopback, 64548);

            SocketAsyncEventArgs args = new SocketAsyncEventArgs();
            args.Completed += new EventHandler<SocketAsyncEventArgs>(connected);
            args.RemoteEndPoint = ipep;

            Task input = new Task(new Action(() =>
            {
                string _in;
                SocketAsyncEventArgs _args = null;
                while ((_in = Console.ReadLine()) != "exit")
                {
                    switch (_in)
                    {
                        case "connect":
                        case "c":
                            { 
                                client.ConnectAsync(args);
                                break;
                            }
                        case "list":
                        case "l":
                            {
                                Console.WriteLine("Getting list...");
                                _args = new SocketAsyncEventArgs();
                                _args.SetBuffer(UTF8.GetBytes(NET_LIST), 0, 8);

                                client.SendAsync(_args);
                                break;
                            }
                    }
                }

                exit = true;
            }));

            input.Start();

            while (!exit)
            {

            }
        }
        protected void StartSend(Socket socket, SocketAsyncEventArgs e)
        {
            bool raiseEvent = false;

            try
            {
                raiseEvent = socket.SendAsync(e);
            }
            catch (Exception exc)
            {
                OnException(new Exception(exc.Message, exc));
                return;
            }

            if (!raiseEvent)
            {
                ProcessSend(e);
            }
        }
        protected void StartSend(Mysocket.Socket socket, SocketAsyncEventArgs e)
        {
            bool raiseEvent = false;

            try
            {
                raiseEvent = socket.SendAsync(e);
            }
            catch (Exception exc)
            {
                OnException(new Exception(exc.Message, exc));
                return;
            }

            if (!raiseEvent)
            {
                ProcessSend(e);
            }
        }
示例#23
0
 public bool send(byte command, string text)
 {
     try
     {
         byte[] sendb = System.Text.Encoding.UTF8.GetBytes(text);
         byte[] lens  = System.Text.Encoding.UTF8.GetBytes(sendb.Length.ToString());
         byte[] b     = new byte[2 + lens.Length + sendb.Length];
         b[0] = command;
         b[1] = (byte)lens.Length;
         lens.CopyTo(b, 2);
         sendb.CopyTo(b, 2 + lens.Length);
         SocketAsyncEventArgs saea = new SocketAsyncEventArgs();
         saea.SetBuffer(b, 0, b.Length);
         tcpc.SendAsync(saea);
     }
     catch { return(false); }
     // tcpc.Close();
     return(true);
 }
        public void TestSslConnect()
        {
            var serverIp = ConfigurationManager.AppSettings["serverIp"];
            var socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            socket.Connect(serverIp, (int)DefaultPorts.SslDirect);
            using (var ns = new NetworkStream(socket))
            {
                var buffer = Encoding.UTF8.GetBytes("hello world!");
                using (var ssls = new SslStream(ns, true, ServerCertificateValidationCallback))
                {
                    ssls.AuthenticateAsClient(serverIp);
                    Console.WriteLine("Is Encrypted: {0}", ssls.IsEncrypted);

                    var saea = new SocketAsyncEventArgs {AcceptSocket = socket};
                    saea.Completed += saea_Completed;
                    saea.SetBuffer(buffer, 0, buffer.Length);
                    socket.SendAsync(saea);
                }
            }
        }
示例#25
0
        public void SendDataToClient(byte type, byte[] data, Socket client)
        {
            //data += Encoding.Unicode.GetBytes("s");
            Message packet = new Message();
            if (!client.Connected)
            {
                Console.WriteLine(client.Handle + " is disconnected");
                DisconnectProc(client);
            }
            else
            {
                //byte[] compressedData = CompressToBytes(data);
                packet.InitSendPacket(type, data);
                SocketAsyncEventArgs _sendArgs = new SocketAsyncEventArgs();
                _sendArgs.SetBuffer(BitConverter.GetBytes(packet.Length), 0, 4);
                _sendArgs.Completed += new EventHandler<SocketAsyncEventArgs>(Send_Completed);
                _sendArgs.UserToken = packet;

                client.SendAsync(_sendArgs);
            }
        }
示例#26
0
        public async Task SendAsync(byte[] data)
        {
            var totalSentBytes = 0;

            while (totalSentBytes < data.Length)
            {
                var offSetData = data.Skip(totalSentBytes).ToArray();
                var sentBytes  = await _socket.SendAsync(offSetData, SocketFlags.None);

                // int sentBytes = await _socket.Send(
                //     data,
                //     totalSentBytes,
                //     data.Length - totalSentBytes,
                //     SocketFlags.None);
                if (sentBytes == 0)
                {
                    throw new SocketException();
                }
                totalSentBytes += sentBytes;
            }
        }
示例#27
0
        internal bool Echo(SocketAsyncEventArgs args)
        {
            int start  = args.Offset;
            int length = _bufferReceiveOffset;
            int total  = args.Buffer.Length;

            if (length > total)
            {
                throw new Exception("数据超出缓冲大小。");
            }

            // SetBuffer修改Offset和Count属性,指定要接收或发送的缓冲区范围。此方法不会更改Buffer属性。
            // 初始化时才调用三个参数的方法,这里调用是错的,会覆盖掉原来设置的缓冲区大小(除非双方交互都是使用固定长度的协议)
            args.SetBuffer(start, length);

            // 发送回客户端
            bool async = _clientSocket.SendAsync(args);

            //
            //args.SetBuffer(start, total);

            return(async);
        }
示例#28
0
        public void Send(IPacket packet)
        {
            lock (locker)
            {
                if (state.Compare(State.Disconnecting))
                {
                    return;
                }

            #if DEBUG
                Console.WriteLine($"received {packet.GetPacketType().ToString()}");
            #endif

                byte[] sendBuffer = PacketSerializer.Serialize(packet);
                socketEventProvider.SendEvent.SetBuffer(sendBuffer, 0, sendBuffer.Length);

                bool willRaiseEvent = socket.SendAsync(socketEventProvider.SendEvent);
                if (willRaiseEvent == false)
                {
                    socketEventProvider.ProcessSend(socketEventProvider.SendEvent);
                }
            }
        }
示例#29
0
        public void send_queue_data()
        {
            try
            {
                while (m_sendQueue.Count > 0)
                {
                    NetworkMsg msg    = m_sendQueue.Dequeue();
                    byte[]     data   = PBSerializer.serialize(msg);
                    byte[]     length = new byte[4];
                    length = BitConverter.GetBytes(data.Length);

                    byte[] packedData = new byte[4 + data.Length];
                    Buffer.BlockCopy(length, 0, packedData, 0, 4);
                    Buffer.BlockCopy(data, 0, packedData, 4, data.Length);
                    m_sendEventArg.SetBuffer(packedData, 0, packedData.Length);
                    m_socket.SendAsync(m_sendEventArg);
                    Log.INFO("client socketId {0} send sucess!", m_socketId);
                }
            }
            catch
            {
                //  close_socket();
                Log.INFO("The connection to the server is broken!");
            }
            //bool willRaiseEvent = m_socket.ReceiveAsync(m_receiveEventArg);
            //if (!willRaiseEvent)
            //{
            //    process_receive(m_receiveEventArg);
            //}

            //m_autoSendEvent.WaitOne();
            //if (!)//投递发送请求,这个函数有可能同步发送出去,这时返回false,并且不会引发SocketAsyncEventArgs.Completed事件
            //{
            //    // 同步发送时处理发送完成事件
            //    process_send(m_socket, m_sendEventArg);
            //}
        }
示例#30
0
        /// <summary>
        /// Sends data asynchronously to a connected <see cref="Socket"/>.
        /// </summary>
        /// <param name="socket"></param>
        /// <param name="buffer"></param>
        /// <param name="offset"></param>
        /// <param name="size"></param>
        /// <param name="socketFlags"></param>
        /// <returns></returns>
        public static Task <int> SendAsync(this Socket socket, byte[] buffer, int offset, int size, SocketFlags socketFlags)
        {
            NotNull(socket, nameof(socket));

            var tcs = new TaskCompletionSource <int>(socket);

#if NETSTANDARD1_3
            var args = new SocketAsyncEventArgs
            {
                SocketFlags = socketFlags,
                UserToken   = tcs
            };
            args.SetBuffer(buffer, offset, size);
            args.Completed += OnSendCompleted;
            if (!socket.SendAsync(args))
            {
                tcs.TrySetSendResult(args);
            }
#else
            socket.BeginSend(buffer, offset, size, socketFlags, BeginSendCallback, tcs);
#endif

            return(tcs.Task);
        }
示例#31
0
 public bool SendAsyncEvent(Socket connectSocket, SocketAsyncEventArgs sendEventArgs, byte[] buffer, int offset, int count)
 {
     if (connectSocket == null)
         return false;
     sendEventArgs.SetBuffer(buffer, offset, count);
     bool willRaiseEvent = connectSocket.SendAsync(sendEventArgs);
     if (!willRaiseEvent)
     {
         return ProcessSend(sendEventArgs);
     }
     else
         return true;
 }
示例#32
0
        public static void Wake(EndPoint endPoint, byte[] macAddress, Action sentAction, Action<System.Net.Sockets.SocketError> failureAction)
        {
            var packet = new List<byte>();
            for (var i = 0; i < 6; i++) // Trailer of 6 FF packets
                packet.Add(0xFF);
            for (var i = 0; i < 16; i++) // Repeat 16 times the MAC address
                packet.AddRange(macAddress);

            var socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
            var args = new SocketAsyncEventArgs();
            args.RemoteEndPoint = endPoint;
            args.Completed += (s, e) =>
            {
#if WPF
                var dispatcher = Dispatcher.CurrentDispatcher;
#else
                var dispatcher = Deployment.Current.Dispatcher; 
#endif

                if (e.SocketError != System.Net.Sockets.SocketError.Success)
                {
                    dispatcher.BeginInvoke(() => failureAction(e.SocketError));
                    return;
                }

                switch (e.LastOperation)
                {
                    case SocketAsyncOperation.Connect:
                        e.SetBuffer(packet.ToArray(), 0, packet.Count);
                        if (!socket.SendAsync(e))
                            dispatcher.BeginInvoke(failureAction);
                        break;
                    case SocketAsyncOperation.Send:
                        dispatcher.BeginInvoke(sentAction);
                        break;
                    default:
                        throw new Exception("Invalid operation completed");
                }
            };
            socket.ConnectAsync(args);
        }
示例#33
0
        /// <summary>
        /// Start sending data
        /// </summary>
        /// <param name="acceptor"></param>
        /// <param name="data"></param>
        /// <param name="token"></param>
        public void StartSend(Socket acceptor, BufferSegment data, object token)
        {
            _senders.Take(sender =>
            {
                if (data.Length > 0 && acceptor.Connected)
                {
                    sender.AcceptSocket = acceptor;
                    sender.SetBuffer(data.Buffer, data.Offset, data.Length);
                    sender.UserToken = token;

                    if (!acceptor.SendAsync(sender))
                    {
                        ProcessSend(sender);
                    }
                }
                else
                {
                    _senders.Release(sender);
                }
            });
        }
示例#34
0
		public void SendAsync_ClosedSocket ()
		{
			Socket s = new Socket (AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
			s.Close ();
			s.SendAsync (null);
		}
示例#35
0
		public void SendAsync_Default ()
		{
			using (Socket s = new Socket (AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)) {
				SocketAsyncEventArgs saea = new SocketAsyncEventArgs ();
				s.SendAsync (saea);
			}
		}
示例#36
0
		static Stream GetPolicyStream (IPEndPoint endpoint)
		{
			MemoryStream ms = new MemoryStream ();
			ManualResetEvent mre = new ManualResetEvent (false);
			// Silverlight only support TCP
			Socket socket = new Socket (endpoint.AddressFamily, SocketType.Stream, ProtocolType.Tcp);

			// Application code can't connect to port 943, so we need a special/internal API/ctor to allow this
			SocketAsyncEventArgs saea = new SocketAsyncEventArgs (true);
			saea.RemoteEndPoint = new IPEndPoint (endpoint.Address, PolicyPort);
			saea.Completed += delegate (object sender, SocketAsyncEventArgs e) {
				if (e.SocketError != SocketError.Success) {
					mre.Set ();
					return;
				}

				switch (e.LastOperation) {
				case SocketAsyncOperation.Connect:
					e.SetBuffer (socket_policy_file_request, 0, socket_policy_file_request.Length);
					socket.SendAsync (e);
					break;
				case SocketAsyncOperation.Send:
					byte [] buffer = new byte [256];
					e.SetBuffer (buffer, 0, buffer.Length);
					socket.ReceiveAsync (e);
					break;
				case SocketAsyncOperation.Receive:
					int transfer = e.BytesTransferred;
					if (transfer > 0) {
						ms.Write (e.Buffer, 0, transfer);
						// Console.Write (Encoding.UTF8.GetString (e.Buffer, 0, transfer));
					}

					if ((transfer == 0) || (transfer < e.Buffer.Length)) {
						ms.Position = 0;
						mre.Set ();
					} else {
						socket.ReceiveAsync (e);
					}
					break;
				}
			};

			socket.ConnectAsync (saea);

			// behave like there's no policy (no socket access) if we timeout
			if (!mre.WaitOne (Timeout))
				return null;

			return ms;
		}
示例#37
0
 bool Utils.Wrappers.Interfaces.ISocket.SendAsync(SocketAsyncEventArgs e)
 {
     return(InternalSocket.SendAsync(e));
 }
示例#38
0
        private bool TryUnsafeSocketOperation(Socket socket, SocketAsyncOperation operation, SocketAsyncEventArgs socketAsyncEventArgs)
        {
            try
            {
                bool result = false;
                switch (operation)
                {
                    case SocketAsyncOperation.Accept:
                        result = socket.AcceptAsync(socketAsyncEventArgs);
                        break;
                    case SocketAsyncOperation.Send:
                        result = socket.SendAsync(socketAsyncEventArgs);
                        break;
                    case SocketAsyncOperation.Receive:
                        result = socket.ReceiveAsync(socketAsyncEventArgs);
                        break;
                    default:
                        throw new InvalidOperationException("Unknown case called, should program something for this");
                }

                if (!result)
                {
                    OperationCallback(socket, socketAsyncEventArgs);
                }
            }
            catch (SocketException ex)
            {
                if (operation != SocketAsyncOperation.Accept)
                {
                    HandleCommunicationError(socket, ex);
                }
                return false;
            }
            catch (ObjectDisposedException)
            {
                // If disposed, handle communication error was already done and we're just catching up on other threads. suppress it.
                return false;
            }

            return true;
        }
示例#39
0
 private bool SentWorker( Socket s, SocketAsyncEventArgs b )
 {
     var index = (int) b.UserToken;
     var isStream = s.SocketType == SocketType.Stream;
     if (isStream){
         while (
         this._isAttacking
         && this._sendLast[ index ]-- > 0
         && ( b.SocketError == SocketError.Success && s.Connected ) )
         try {
             //this.RefreshSendData( index );
             if ( s.SendAsync( this._sendArgs[ index ] ) ) return true;
         }
         catch { }
     }
     else {
         while ( this._isAttacking ) {
             try {
                 if ( s.SendToAsync( this._sendArgs[ index ] ) ) return true; //prevent stack overflow
             }
             catch { }
         }
     }
     return !this._isAttacking && b.SocketError == SocketError.Success;
 }
示例#40
0
        /// <summary>
        /// Begins the network communication required to retrieve the time from the NTP server
        /// </summary>
        public void RequestTime()
        {
            byte[] buffer = new byte[48];
            buffer[0] = 0x1B;
            for (var i = 1; i < buffer.Length; ++i)
                buffer[i] = 0;
            DnsEndPoint _endPoint = new DnsEndPoint(_serverName, 123);

            _socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
            SocketAsyncEventArgs sArgsConnect = new SocketAsyncEventArgs() { RemoteEndPoint = _endPoint };
            sArgsConnect.Completed += (o, e) =>
                                          {
                                              if (e.SocketError == SocketError.Success)
                                              {
                                                  SocketAsyncEventArgs sArgs = new SocketAsyncEventArgs()
                                                                                   {RemoteEndPoint = _endPoint};
                                                  sArgs.Completed +=
                                                      new EventHandler<SocketAsyncEventArgs>(sArgs_Completed);
                                                  sArgs.SetBuffer(buffer, 0, buffer.Length);
                                                  sArgs.UserToken = buffer;
                                                  _socket.SendAsync(sArgs);
                                              }
                                          };
            _socket.ConnectAsync(sArgsConnect);
        }
示例#41
0
 private bool ConnectedWorker( Socket s, SocketAsyncEventArgs b )
 {
     var index = (int) b.UserToken;
     if ( !this._isAttacking ) return true;
     while ( this._sendLast[ index ]-- > 0UL ) {
         this.RefreshSendData( index );
         if ( s.SendAsync( this._sendArgs[ index ] ) )
             return true;
     }
     return false;
 }
        public async Task SocketCanReadAndWrite()
        {
            var loop = new UvLoopHandle(_logger);
            loop.Init(_uv);
            var tcp = new UvTcpHandle(_logger);
            tcp.Init(loop);
            var address = ServerAddress.FromUrl("http://localhost:54321/");
            tcp.Bind(address);
            tcp.Listen(10, (_, status, error, state) =>
            {
                Console.WriteLine("Connected");
                var tcp2 = new UvTcpHandle(_logger);
                tcp2.Init(loop);
                tcp.Accept(tcp2);
                var data = Marshal.AllocCoTaskMem(500);
                tcp2.ReadStart(
                    (a, b, c) => tcp2.Libuv.buf_init(data, 500),
                    (__, nread, state2) =>
                    {
                        if (nread <= 0)
                        {
                            tcp2.Dispose();
                        }
                        else
                        {
                            for (var x = 0; x < 2; x++)
                            {
                                var req = new UvWriteReq(new KestrelTrace(new TestKestrelTrace()));
                                req.Init(loop);
                                var block = MemoryPoolBlock2.Create(
                                    new ArraySegment<byte>(new byte[] { 65, 66, 67, 68, 69 }),
                                    dataPtr: IntPtr.Zero,
                                    pool: null,
                                    slab: null);
                                var start = new MemoryPoolIterator2(block, 0);
                                var end = new MemoryPoolIterator2(block, block.Data.Count);
                                req.Write(
                                    tcp2,
                                    start,
                                    end,
                                    1,
                                    (_1, _2, _3, _4) =>
                                    {
                                        block.Unpin();
                                    },
                                    null);
                            }
                        }
                    },
                    null);
                tcp.Dispose();
            }, null);
            Console.WriteLine("Task.Run");
            var t = Task.Run(async () =>
            {
                var socket = new Socket(
                    AddressFamily.InterNetwork,
                    SocketType.Stream,
                    ProtocolType.Tcp);
#if DNX451
                await Task.Factory.FromAsync(
                    socket.BeginConnect,
                    socket.EndConnect,
                    new IPEndPoint(IPAddress.Loopback, 54321),
                    null,
                    TaskCreationOptions.None);
                await Task.Factory.FromAsync(
                    socket.BeginSend,
                    socket.EndSend,
                    new[] { new ArraySegment<byte>(new byte[] { 1, 2, 3, 4, 5 }) },
                    SocketFlags.None,
                    null,
                    TaskCreationOptions.None);
#else
                await socket.ConnectAsync(new IPEndPoint(IPAddress.Loopback, 54321));
                await socket.SendAsync(new[] { new ArraySegment<byte>(new byte[] { 1, 2, 3, 4, 5 }) },
                                       SocketFlags.None);
#endif
                socket.Shutdown(SocketShutdown.Send);
                var buffer = new ArraySegment<byte>(new byte[2048]);
                while (true)
                {
#if DNX451
                    var count = await Task.Factory.FromAsync(
                        socket.BeginReceive,
                        socket.EndReceive,
                        new[] { buffer },
                        SocketFlags.None,
                        null,
                        TaskCreationOptions.None);
#else
                    var count = await socket.ReceiveAsync(new[] { buffer }, SocketFlags.None);
#endif
                    Console.WriteLine("count {0} {1}",
                        count,
                        System.Text.Encoding.ASCII.GetString(buffer.Array, 0, count));
                    if (count <= 0) break;
                }
                socket.Dispose();
            });
            loop.Run();
            loop.Dispose();
            await t;
        }
        public async Task SocketCanRead()
        {
            var loop = new UvLoopHandle(_logger);
            loop.Init(_uv);
            var tcp = new UvTcpHandle(_logger);
            tcp.Init(loop);
            var address = ServerAddress.FromUrl("http://localhost:54321/");
            tcp.Bind(address);
            tcp.Listen(10, (_, status, error, state) =>
            {
                Console.WriteLine("Connected");
                var tcp2 = new UvTcpHandle(_logger);
                tcp2.Init(loop);
                tcp.Accept(tcp2);
                var data = Marshal.AllocCoTaskMem(500);
                tcp2.ReadStart(
                    (a, b, c) => _uv.buf_init(data, 500),
                    (__, nread, state2) =>
                    {
                        if (nread <= 0)
                        {
                            tcp2.Dispose();
                        }
                    },
                    null);
                tcp.Dispose();
            }, null);
            Console.WriteLine("Task.Run");
            var t = Task.Run(async () =>
            {
                var socket = new Socket(
                    AddressFamily.InterNetwork,
                    SocketType.Stream,
                    ProtocolType.Tcp);
#if DNX451
                await Task.Factory.FromAsync(
                    socket.BeginConnect,
                    socket.EndConnect,
                    new IPEndPoint(IPAddress.Loopback, 54321),
                    null,
                    TaskCreationOptions.None);
                await Task.Factory.FromAsync(
                    socket.BeginSend,
                    socket.EndSend,
                    new[] { new ArraySegment<byte>(new byte[] { 1, 2, 3, 4, 5 }) },
                    SocketFlags.None,
                    null,
                    TaskCreationOptions.None);
#else
                await socket.ConnectAsync(new IPEndPoint(IPAddress.Loopback, 54321));
                await socket.SendAsync(new[] { new ArraySegment<byte>(new byte[] { 1, 2, 3, 4, 5 }) },
                                       SocketFlags.None);
#endif
                socket.Dispose();
            });
            loop.Run();
            loop.Dispose();
            await t;
        }
示例#44
0
文件: SocketTest.cs 项目: dfr0/moon
		public void SendAsync ()
		{
			Socket s = new Socket (AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

			Assert.Throws<NullReferenceException> (delegate {
				s.SendAsync (null);
			}, "null");

			SocketAsyncEventArgs saea = new SocketAsyncEventArgs ();
			Assert.Throws<NullReferenceException> (delegate {
				s.SendAsync (saea);
			}, "SocketAsyncEventArgs");

			saea.SetBuffer (null, 0, 0);
			Assert.Throws<NullReferenceException> (delegate {
				s.SendAsync (saea);
			}, "SetBuffer / null");

			s.Close ();
			Assert.Throws<ObjectDisposedException> (delegate {
				s.SendAsync (saea);
			}, "Closed");
		}
示例#45
0
        public void SendMsg(Socket conn, SocketAsyncEventArgs args, byte[] data, int length)
        {
            if (null == conn)
            {
                Console.WriteLine("Send msg failed, send socket is null");
                return;
            }

            args.SetBuffer(data, 0, length);
            if (!conn.SendAsync(args))
            {
                ProcessSend(args);
            }
        }
示例#46
0
 public static Task <int> SendAsync(this Socket socket, ArraySegment <byte> buffer, SocketFlags socketFlags) =>
 socket.SendAsync(buffer, socketFlags, wrapExceptionsInIOExceptions: false);
示例#47
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;
        }
        protected void StartSend(Socket socket, SocketAsyncEventArgs e)
        {
            if (socket == null)
            {
                throw new ArgumentNullException("socket");
            }

            if (e == null)
            {
                throw new ArgumentNullException("e");
            }

            bool raiseEvent = false;

            try
            {
                raiseEvent = socket.SendAsync(e);
            }
            catch (Exception exc)
            {
                this.OnException(new Exception(exc.Message, exc));
                return;
            }

            if (!raiseEvent)
            {
                this.ProcessSend(e);
            }
        }
示例#49
0
        internal void PerformHandShakeWithServer(Socket socket, Action completed, Action failed)
        {
            try
            {
                _handshakeCompleted = completed;
                _handshakeFailed = failed;
                var handshakeBuffer = GenerateC2SRequest();
                var sendHandshakeEventArg = new SocketAsyncEventArgs();
                sendHandshakeEventArg.RemoteEndPoint = socket.RemoteEndPoint;
                sendHandshakeEventArg.SetBuffer(handshakeBuffer, 0, handshakeBuffer.Length);

                var receiveHandshakeResponseEventArg = new SocketAsyncEventArgs();
                receiveHandshakeResponseEventArg.RemoteEndPoint = socket.RemoteEndPoint;
                receiveHandshakeResponseEventArg.SetBuffer(new Byte[WebSocketConstants.MAX_RECEIVE_BUFFER_SIZE], 0, WebSocketConstants.MAX_RECEIVE_BUFFER_SIZE);
                var handshakeResponse = new Collection<byte>();

                sendHandshakeEventArg.Completed += (sender, args) =>
                {
                    if (args.SocketError == SocketError.Success)
                    {
                        socket.ReceiveAsync(receiveHandshakeResponseEventArg);
                    }
                };
                receiveHandshakeResponseEventArg.Completed += (sender, args) =>
                {
                    if (args.SocketError == SocketError.Success)
                    {
                        var handshakeComplete = false;
                        for (int i = 0; i < args.BytesTransferred; i++)
                        {
                            handshakeResponse.Add(args.Buffer[i]);
                            if (handshakeResponse.Count > 4 && ((int)handshakeResponse[handshakeResponse.Count - 4]).Equals(0x0D) && ((int)handshakeResponse[handshakeResponse.Count - 3]).Equals(0x0A) && ((int)handshakeResponse[handshakeResponse.Count - 2]).Equals(0x0D) && ((int)handshakeResponse[handshakeResponse.Count - 1]).Equals(0x0A))
                            {
                                handshakeComplete = true;
                                break;
                            }
                        }
                        if (handshakeComplete)
                        {
                            try
                            {
                                VerifyS2CResponse(handshakeResponse.ToArray());
                                completed();
                            }
                            catch (WebSocketException)
                            {
                                //TODO - log exception
                                failed();
                            }

                        }
                        else
                        {
                            socket.ReceiveAsync(receiveHandshakeResponseEventArg);
                        }
                    }
                    else
                    {
                        failed();
                    }
                };
                Debug.WriteLine("Sending Handshake");
                socket.SendAsync(sendHandshakeEventArg);
            }
            catch (Exception)
            {
                //TODO - log exception
                failed();
            }
        }
示例#50
0
        public static void ReestabilishConnection()
        {
            if (SelectedServer != null && ServerSocket != null && !ServerSocket.Connected)
            {
                Debug.WriteLine("Reestabilishing connection");
                SocketError result = SocketError.Fault;
                Socket _socket = null;
                ManualResetEvent _clientDone = new ManualResetEvent(false);

                DnsEndPoint hostEntry = new DnsEndPoint(SelectedServer.Address, SelectedServer.Port);

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

                SocketAsyncEventArgs socketEventArg = new SocketAsyncEventArgs();
                socketEventArg.RemoteEndPoint = hostEntry;

                socketEventArg.Completed += new EventHandler<SocketAsyncEventArgs>(delegate(object s, SocketAsyncEventArgs e)
                {

                    result = e.SocketError;

                    if (!result.Equals(SocketError.Success) && OnConnectionFailed != null)
                        OnConnectionFailed();
                    _clientDone.Set();
                });

                _clientDone.Reset();

                _socket.ConnectAsync(socketEventArg);

                _clientDone.WaitOne(2000);

                if (_socket != null && _socket.Connected)
                {
                    SocketAsyncEventArgs toBeSent = new SocketAsyncEventArgs();
                    toBeSent.RemoteEndPoint = _socket.RemoteEndPoint;
                    toBeSent.UserToken = null;
                    byte[] payload = IntroductionMessage.GetMessage();
                    toBeSent.SetBuffer(payload, 0, payload.Length);
                    _socket.SendAsync(toBeSent);
                    ServersStorage.ServerSocket = _socket;
                }
            }
        }
示例#51
0
 public static Task <int> SendAsync(this Socket socket, IList <ArraySegment <byte> > buffers, SocketFlags socketFlags) =>
 socket.SendAsync(buffers, socketFlags);
示例#52
0
		public void SendAsync_Null ()
		{
			using (Socket s = new Socket (AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)) {
				s.SendAsync (null);
			}
		}
示例#53
0
        internal static void SendTcp(Socket s, byte[] msg, int len, IPEndPoint EP)
        {
            string response = "Operation Timeout";

            if (s != null)
            {
                // Create SocketAsyncEventArgs context object
                SocketAsyncEventArgs socketEventArg = new SocketAsyncEventArgs();

                // Set properties on context object
                socketEventArg.RemoteEndPoint = EP;
                socketEventArg.UserToken = null;

                // Inline event handler for the Completed event.
                // Note: This event handler was implemented inline in order to make this method self-contained.
                socketEventArg.Completed += new EventHandler<SocketAsyncEventArgs>(delegate(object ss, SocketAsyncEventArgs e)
                {
                    response = e.SocketError.ToString();

                    // Unblock the UI thread
                    try
                    {
                        _clientDone[s].Set();
                    }
                    catch (KeyNotFoundException)
                    {
                    }
                });

                // Add the data to be sent into the buffer
                socketEventArg.SetBuffer(msg, 0, len);

                // Sets the state of the event to nonsignaled, causing threads to block
                _clientDone[s].Reset();

                // Make an asynchronous Send request over the socket
                if (s.SendAsync(socketEventArg) == false)
                {
                    response = socketEventArg.SocketError.ToString();

                    // Unblock the UI thread
                    try
                    {
                        _clientDone[s].Set();
                    }
                    catch (KeyNotFoundException)
                    {
                    }
                }

                // Block the UI thread for a maximum of TIMEOUT_MILLISECONDS milliseconds.
                // If no response comes back within this time then proceed
                _clientDone[s].WaitOne(TimeOut);
            }
        }
示例#54
0
		public void SendAsync_NullBuffer ()
		{
			using (Socket s = new Socket (AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)) {
				SocketAsyncEventArgs saea = new SocketAsyncEventArgs ();
				saea.SetBuffer (null, 0, 0);
				s.SendAsync (null);
			}
		}
        public async Task TestCommonOperations()
        {
            // Listen.
            using (var listener = new Socket(SocketType.Stream, ProtocolType.Tcp))
            {
                listener.Bind(new IPEndPoint(IPAddress.IPv6Any, 0));
                listener.Listen(1);
                var acceptReceiveTask = Task.Run(async () =>
                {
                    // Accept.
                    Socket accepted;
                    using (var acceptAwaitable = new SocketAwaitable())
                    {
                        Assert.IsNull(acceptAwaitable.AcceptSocket);

                        var acceptResult = await listener.AcceptAsync(acceptAwaitable);
                        Assert.AreEqual(acceptResult, SocketError.Success);
                        Assert.IsNotNull(acceptAwaitable.AcceptSocket);
                        accepted = acceptAwaitable.AcceptSocket;
                    }

                    // Receive.
                    using (var receiveAwaitable = new SocketAwaitable())
                    {
                        receiveAwaitable.Buffer = new ArraySegment<byte>(new byte[16], 2, 14);

                        var receiveResult = await accepted.ReceiveAsync(receiveAwaitable);
                        Assert.AreEqual(receiveResult, SocketError.Success);
                        Assert.AreEqual(receiveAwaitable.Transferred.Count, 1);
                        Assert.AreEqual(receiveAwaitable.Buffer.Array[receiveAwaitable.Buffer.Offset], 7);
                    }
                });

                // Connect.
                using (var client = new Socket(SocketType.Stream, ProtocolType.Tcp))
                {
                    using (var connectAwaitable = new SocketAwaitable())
                    {
                        connectAwaitable.RemoteEndPoint = new IPEndPoint(IPAddress.IPv6Loopback, (listener.LocalEndPoint as IPEndPoint).Port);

                        var connectResult = await client.ConnectAsync(connectAwaitable);
                        Assert.AreEqual(connectResult, SocketError.Success);
                    }

                    await Task.Delay(500);

                    // Send.
                    using (var sendAwaitable = new SocketAwaitable())
                    {
                        sendAwaitable.Buffer = new ArraySegment<byte>(new byte[] { 0, 1, 2, 3, 4, 5, 6, 7 }, 7, 1);

                        var sendResult = await client.SendAsync(sendAwaitable);
                        Assert.AreEqual(sendResult, SocketError.Success);
                    }

                    // Await accept/receive task.
                    await acceptReceiveTask;
                    Assert.AreEqual(acceptReceiveTask.Status, TaskStatus.RanToCompletion);
                }
            }
        }
示例#56
0
        private void SendMessageFinal(Socket destination, byte[] data)
        {
            SocketAsyncEventArgs args = new SocketAsyncEventArgs();
            args.Completed += OnIOCompleted;
            args.SetBuffer(data, 0, data.Length);
            args.RemoteEndPoint = destination.RemoteEndPoint;

            try
            {
                if (!destination.SendAsync(args))
                    ProcessSend(args);
            }
            catch (Exception ex)
            {
                m_log.Warn("Failed to send data to " + destination.RemoteEndPoint + ": " + ex.Message);
            }
        }
示例#57
0
 public static Task <int> SendAsync(this Socket socket, ArraySegment <byte> buffer, SocketFlags socketFlags) =>
 socket.SendAsync(buffer, socketFlags, fromNetworkStream: false);
示例#58
0
        private void Connect()
        {
            if (ServersStorage.ServerSocket != null)
            {
                ServersStorage.SelectedServer = null;
                if (ServersStorage.ServerSocket.Connected)
                    ServersStorage.ServerSocket.Close();
                ServersStorage.ServerSocket = null;
            }
            SocketError result = SocketError.Fault;
            Socket _socket = null;
            ManualResetEvent _clientDone = new ManualResetEvent(false);

            DnsEndPoint hostEntry = new DnsEndPoint(hostName, portNumber);
 
            _socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

            SocketAsyncEventArgs socketEventArg = new SocketAsyncEventArgs();
            socketEventArg.RemoteEndPoint = hostEntry;

            socketEventArg.Completed += new EventHandler<SocketAsyncEventArgs>(delegate(object s, SocketAsyncEventArgs e)
            {
                
                result = e.SocketError;

                if (!result.Equals(SocketError.Success))
                    Dispatcher.BeginInvoke(delegate() { MessageBox.Show("Failed to connect"); });
                else
                {
                    Dispatcher.BeginInvoke(delegate() { NavigationService.GoBack(); });
                }
                _clientDone.Set();
            });

            _clientDone.Reset();

            _socket.ConnectAsync(socketEventArg);

            _clientDone.WaitOne(2000);

            if (_socket != null && _socket.Connected)
            {
                SocketAsyncEventArgs toBeSent = new SocketAsyncEventArgs();
                toBeSent.RemoteEndPoint = _socket.RemoteEndPoint;
                toBeSent.UserToken = null;
                byte[] payload = IntroductionMessage.GetMessage();
                toBeSent.SetBuffer(payload, 0, payload.Length);
                _socket.SendAsync(toBeSent);
                ServersStorage.ServerSocket = _socket;
                ServersStorage.SelectedServer = new ServerData(host, hostName, portNumber);
            }
        }
示例#59
0
 public static ValueTask <int> SendAsync(this Socket socket, ReadOnlyMemory <byte> buffer, SocketFlags socketFlags, CancellationToken cancellationToken = default) =>
 socket.SendAsync(buffer, socketFlags, cancellationToken);