当前位置: 首页>>代码示例>>C#>>正文


C# Socket.SendAsync方法代码示例

本文整理汇总了C#中System.Net.Sockets.Socket.SendAsync方法的典型用法代码示例。如果您正苦于以下问题:C# Socket.SendAsync方法的具体用法?C# Socket.SendAsync怎么用?C# Socket.SendAsync使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在System.Net.Sockets.Socket的用法示例。


在下文中一共展示了Socket.SendAsync方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。

示例1: SendMessage

        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;
            });
        }
开发者ID:TeamnetGroup,项目名称:Redis.SilverlightClient,代码行数:33,代码来源:SocketTransmitter.cs

示例2: SendTimeRequest

		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));
			}
		}
开发者ID:Yortw,项目名称:Yort.Ntp,代码行数:52,代码来源:NtpClientStandardSockets.cs

示例3: SendMessage

 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();
 }
开发者ID:Dnigor,项目名称:Multitier,代码行数:16,代码来源:Messager.cs

示例4: Main

        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)
            {

            }
        }
开发者ID:Honsal,项目名称:CoolPunchClientForTest,代码行数:46,代码来源:Program.cs

示例5: StartSend

        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);
            }
        }
开发者ID:ChuckFork,项目名称:SuperSocket.ClientEngine,代码行数:19,代码来源:ProxyConnectorBase.cs

示例6: TestSslConnect

        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);
                }
            }
        }
开发者ID:brantburnett,项目名称:couchbase-net-client,代码行数:20,代码来源:SSLConnectionTests.cs

示例7: SendDataToClient

        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);
            }
        }
开发者ID:Ilumia,项目名称:TheVampire_server,代码行数:21,代码来源:Communication.cs

示例8: StartSend

        /// <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);
                }
            });
        }
开发者ID:badgerodon,项目名称:event-driven,代码行数:27,代码来源:TcpServer.cs

示例9: SendAsyncEvent

 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;
 }
开发者ID:Donnie888,项目名称:LxServer,代码行数:13,代码来源:AsyncSocketServer.cs

示例10: RequestTime

        /// <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);
        }
开发者ID:Anheledir,项目名称:authenticator-plus,代码行数:28,代码来源:NtpClient.cs

示例11: SendAsync_NullBuffer

		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);
			}
		}
开发者ID:Therzok,项目名称:mono,代码行数:8,代码来源:SocketTest.cs

示例12: SendAsync_Null

		public void SendAsync_Null ()
		{
			using (Socket s = new Socket (AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)) {
				s.SendAsync (null);
			}
		}
开发者ID:Therzok,项目名称:mono,代码行数:6,代码来源:SocketTest.cs

示例13: TryUnsafeSocketOperation

        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;
        }
开发者ID:tablesmit,项目名称:simplsockets,代码行数:41,代码来源:SimplSocketServer.cs

示例14: SendMsg

        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);
            }
        }
开发者ID:eliteYang,项目名称:NFNet,代码行数:14,代码来源:NFServer.cs

示例15: SendTcp

        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);
            }
        }
开发者ID:abraxas4,项目名称:AR-Drone-Project,代码行数:55,代码来源:NetworkHelper.cs


注:本文中的System.Net.Sockets.Socket.SendAsync方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。