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


C# UdpClient.BeginSend方法代码示例

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


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

示例1: ServerContext

        public ServerContext(int port, int maxclients, ref List<string> TextStack, string OwnIP)
        {
            BeginSendUdpServerCallback = new AsyncCallback(OnBeginSendUdpServerCallbackFinished);
            ServerMessage = System.Text.Encoding.ASCII.GetBytes("OK:" + OwnIP);

            UdpServer = new UdpClient(new IPEndPoint(IPAddress.Any, 8011)); //da bei xp fehler

            UdpServer.JoinMulticastGroup(BroadcastServer.Address);

            UdpServer.BeginSend(ServerMessage, ServerMessage.Length, BroadcastServer, BeginSendUdpServerCallback, null);

            MaxClients = maxclients;

            Ip = IPAddress.Any;
            this.Port = port;

            listener = new TcpListener(Ip, Port);
            Clients = new List<ClientContext>(MaxClients);

            listener.Start();

            BeginAcceptSocketCallback = new AsyncCallback(OnClientConnected);

            this.TextStack = TextStack;
        }
开发者ID:janis2013,项目名称:TextVerteilerServerDns,代码行数:25,代码来源:ServerContext.cs

示例2: EndGetHostAddress

	    private void EndGetHostAddress(IAsyncResult asyncResult)
        {
	        var state = (State) asyncResult.AsyncState;
	        try
	        {
	            var addresses = Dns.EndGetHostAddresses(asyncResult);
	            var endPoint = new IPEndPoint(addresses[0], 123);

	            var socket = new UdpClient();
	            socket.Connect(endPoint);
	            socket.Client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReceiveTimeout, 500);
	            socket.Client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.SendTimeout, 500);
	            var sntpData = new byte[SntpDataLength];
	            sntpData[0] = 0x1B; // version = 4 & mode = 3 (client)

	        	var newState = new State(socket, endPoint, state.GetTime, state.Failure);
	        	var result = socket.BeginSend(sntpData, sntpData.Length, EndSend, newState);
				RegisterWaitForTimeout(newState, result);
	        }
	        catch (Exception)
	        {
                // retry, recursion stops at the end of the hosts
                BeginGetDate(state.GetTime, state.Failure);
	
	        }
	    }
开发者ID:ferventcoder,项目名称:rhino-licensing,代码行数:26,代码来源:SntpClient.cs

示例3: Send

 public void Send()
 {
     var msg = Encoding.ASCII.GetBytes(Message);
       try {
     var client = new UdpClient();
     client.Client.Bind(new IPEndPoint(LocalAddress, 0));
     client.Ttl = 10;
     client.Client.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.MulticastTimeToLive, 10);
     client.BeginSend(msg, msg.Length, EndPoint, result =>
     {
       try {
     client.EndSend(result);
       }
       catch (Exception ex) {
     _logger.Debug(ex);
       }
       finally {
     try {
       client.Close();
     }
     catch (Exception) {
     }
       }
     }, null);
       }
       catch (Exception ex) {
     _logger.Error(ex);
       }
       ++SendCount;
 }
开发者ID:vitska,项目名称:simpleDLNA,代码行数:30,代码来源:Datagram.cs

示例4: Send

 public void Send()
 {
   var msg = Encoding.ASCII.GetBytes(Message);
   try {
     var client = new UdpClient();
     client.Client.Bind(new IPEndPoint(LocalAddress, 0));
     client.BeginSend(msg, msg.Length, EndPoint, result =>
     {
       try {
         client.EndSend(result);
       }
       catch (Exception ex) {
         Debug(ex);
       }
       finally {
         try {
           client.Close();
         }
         catch (Exception) {
         }
       }
     }, null);
   }
   catch (Exception ex) {
     Error(ex);
   }
   ++SendCount;
 }
开发者ID:itsmevix,项目名称:FTT-DLNA,代码行数:28,代码来源:Datagram.cs

示例5: Send

 public void Send()
 {
     var msg = Encoding.ASCII.GetBytes(Message);
       foreach (var external in IP.ExternalIPAddresses) {
     try {
       var client = new UdpClient(new IPEndPoint(external, 0));
       client.BeginSend(msg, msg.Length, EndPoint, result =>
       {
     try {
       client.EndSend(result);
     }
     catch (Exception ex) {
       Debug(ex);
     }
     finally {
       try {
         client.Close();
       }
       catch (Exception) {
       }
     }
       }, null);
     }
     catch (Exception ex) {
       Error(ex);
     }
       }
       ++SendCount;
 }
开发者ID:rodionovstepan,项目名称:simpleDLNA,代码行数:29,代码来源:Datagram.cs

示例6: Connect

 public static void Connect()
 {
     UdpClient client = new UdpClient();
     ep = new IPEndPoint(IPAddress.Parse(Address), Port);
     client.Connect(ep);
     Byte[] data = Encoding.ASCII.GetBytes(requestType["Container"]);
     client.BeginSend(data, data.Length, new AsyncCallback(SendCallback), client);            
     client.BeginReceive(new AsyncCallback(ReceiveCallBack), client);            
 }
开发者ID:rwalicki,项目名称:inteligentny_dom,代码行数:9,代码来源:UDPConnection.cs

示例7: BeginSend_AsyncOperationCompletes_Success

        public void BeginSend_AsyncOperationCompletes_Success()
        {
            UdpClient udpClient = new UdpClient();
            byte[] sendBytes = new byte[1];
            IPEndPoint remoteServer = new IPEndPoint(IPAddress.Loopback, TestPortBase + 2);
            _waitHandle.Reset();
            udpClient.BeginSend(sendBytes, sendBytes.Length, remoteServer, new AsyncCallback(AsyncCompleted), udpClient);

            Assert.True(_waitHandle.WaitOne(5000), "Timed out while waiting for connection");
        }
开发者ID:s0ne0me,项目名称:corefx,代码行数:10,代码来源:UdpClientTest.cs

示例8: BeginSend_NegativeBytes_Throws

        public void BeginSend_NegativeBytes_Throws()
        {
            UdpClient udpClient = new UdpClient();
            byte[] sendBytes = new byte[1];
            IPEndPoint remoteServer = new IPEndPoint(IPAddress.Loopback, UnusedPort);

            Assert.Throws<ArgumentOutOfRangeException>("bytes", () =>
            {
                udpClient.BeginSend(sendBytes, -1, remoteServer, new AsyncCallback(AsyncCompleted), udpClient);
            });
        }
开发者ID:nnyamhon,项目名称:corefx,代码行数:11,代码来源:UdpClientTest.cs

示例9: BeginSend_BytesMoreThanArrayLength_Throws

        public void BeginSend_BytesMoreThanArrayLength_Throws()
        {
            UdpClient udpClient = new UdpClient();
            byte[] sendBytes = new byte[1];
            IPEndPoint remoteServer = new IPEndPoint(IPAddress.Loopback, TestPortBase + 1);

            Assert.Throws<ArgumentOutOfRangeException>("bytes", () =>
            {
                udpClient.BeginSend(sendBytes, sendBytes.Length + 1, remoteServer, new AsyncCallback(AsyncCompleted), udpClient);
            });
        }
开发者ID:s0ne0me,项目名称:corefx,代码行数:11,代码来源:UdpClientTest.cs

示例10: send

 IEnumerator send(string server, string message)
 {
     Debug.Log("sending..");
     var u = new System.Net.Sockets.UdpClient();
     u.EnableBroadcast = true;
     u.Connect(server, listenPort);
     var sendBytes = System.Text.Encoding.ASCII.GetBytes(message);
     sent = false;
     u.BeginSend(sendBytes, sendBytes.Length,
         new System.AsyncCallback(SendCallback), u);
     while (!sent) {
         yield return null;
     }
     u.Close();
     coroutine_ = null;
     Debug.Log("done.");
 }
开发者ID:gear,项目名称:PLB-2015F-ARGame,代码行数:17,代码来源:SendUDP.cs

示例11: Send

        /// <summary>
        /// UDP发送
        /// </summary>
        /// <param name="ip">IP</param>
        /// <param name="port">端口</param>
        /// <param name="data">发送内容</param>
        public void Send(string ip, int port, string data)
        {
            try
            {
                IPEndPoint sendEP = new IPEndPoint(IPAddress.Parse(ip), port);
                UdpClient udpSend = new UdpClient();

                UdpState udpSendState = new UdpState();
                udpSendState.ipEndPoint = sendEP;
                udpSend.Connect(udpSendState.ipEndPoint);
                udpSendState.udpClient = udpSend;

                Byte[] sendBytes = Encoding.GetEncoding("UTF-8").GetBytes(data);
                udpSend.BeginSend(sendBytes, sendBytes.Length, new AsyncCallback(SendCallback), udpSendState);
            }
            catch
            {

            }
        }
开发者ID:micro-potato,项目名称:RoboticArm,代码行数:26,代码来源:AsyncUDP.cs

示例12: FindServer

        /// <summary>
        /// Attemps to discover the server within a local network
        /// </summary>
        public void FindServer(Action<IPEndPoint> onSuccess)
        {
            // Create a udp client
            var client = new UdpClient(new IPEndPoint(IPAddress.Any, GetRandomUnusedPort()));

            // Construct the message the server is expecting
            var bytes = Encoding.UTF8.GetBytes(broadcastDiscoverMessage);

            // Send it - must be IPAddress.Broadcast, 7359
            var targetEndPoint = new IPEndPoint(IPAddress.Broadcast, 7359);

            // Send it
            client.BeginSend(bytes, bytes.Length, targetEndPoint, iac => {
                    
                //client.EndReceive
                    client.BeginReceive(iar =>
                    {
                        IPEndPoint remoteEndPoint= null;
                        var result = client.EndReceive(iar, ref remoteEndPoint);
                        if (remoteEndPoint.Port == targetEndPoint.Port)
                        {
                            // Convert bytes to text
                            var text = Encoding.UTF8.GetString(result);

                            // Expected response : MediaBrowserServer|192.168.1.1:1234
                            // If the response is what we're expecting, proceed
                            if (text.StartsWith("mediabrowserserver", StringComparison.OrdinalIgnoreCase))
                            {
                                text = text.Split('|')[1];
                                var vals = text.Split(':');
                                onSuccess(new IPEndPoint(IPAddress.Parse(vals[0]), int.Parse(vals[1])));
                            }
                        }
                    }, client);
                }, client);
        }
开发者ID:rrb008,项目名称:MediaBrowser.ApiClient,代码行数:39,代码来源:ServerLocator.cs

示例13: SendPacket

		private void SendPacket(UdpClient Client, IPEndPoint Destination, byte[] Packet)
		{
			Client.BeginSend(Packet, Packet.Length, Destination, this.EndSend, Client);
		}
开发者ID:PeterWaher,项目名称:RetroSharp,代码行数:4,代码来源:UPnPClient.cs

示例14: GetDateAsync

        public Task<DateTime> GetDateAsync()
        {
            index++;
            if (hosts.Length <= index)
            {
                throw new InvalidOperationException(
                    "After trying out all the hosts, was unable to find anyone that could tell us what the time is");
            }
            var host = hosts[index];
            return Task.Factory.FromAsync<IPAddress[]>((callback, state) => Dns.BeginGetHostAddresses(host, callback, state),
                                                Dns.EndGetHostAddresses, host)
                .ContinueWith(hostTask =>
                {
                    if (hostTask.IsFaulted)
                    {
                        log.DebugException("Could not get time from: " + host, hostTask.Exception);
                        return GetDateAsync();
                    }
                    var endPoint = new IPEndPoint(hostTask.Result[0], 123);


                    var socket = new UdpClient();
                    socket.Connect(endPoint);
                    socket.Client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReceiveTimeout, 500);
                    socket.Client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.SendTimeout, 500);
                    var sntpData = new byte[SntpDataLength];
                    sntpData[0] = 0x1B; // version = 4 & mode = 3 (client)
                    return Task.Factory.FromAsync<int>(
                        (callback, state) => socket.BeginSend(sntpData, sntpData.Length, callback, state),
                        socket.EndSend, null)
                               .ContinueWith(sendTask =>
                               {
                                   if (sendTask.IsFaulted)
                                   {
                                       try
                                       {
                                           socket.Close();
                                       }
                                       catch (Exception)
                                       {
                                       }
                                       log.DebugException("Could not send time request to : " + host, sendTask.Exception);
                                       return GetDateAsync();
                                   }

                                   return Task.Factory.FromAsync<byte[]>(socket.BeginReceive, (ar) => socket.EndReceive(ar, ref endPoint), null)
                                              .ContinueWith(receiveTask =>
                                              {
                                                  if (receiveTask.IsFaulted)
                                                  {
                                                      try
                                                      {
                                                          socket.Close();
                                                      }
                                                      catch (Exception)
                                                      {
                                                      }
                                                      log.DebugException("Could not get time response from: " + host, receiveTask.Exception);
                                                      return GetDateAsync();
                                                  }
                                                  var result = receiveTask.Result;
                                                  if (IsResponseValid(result) == false)
                                                  {
                                                      log.Debug("Did not get valid time information from " + host);
                                                      return GetDateAsync();
                                                  }
                                                  var transmitTimestamp = GetTransmitTimestamp(result);
                                                  return new CompletedTask<DateTime>(transmitTimestamp);
                                              }).Unwrap();
                               }).Unwrap();
                }).Unwrap();
        }
开发者ID:heinnge,项目名称:ravendb,代码行数:72,代码来源:SntpClient.cs

示例15: runCheck

        /* return values
         * 0 = check ok
         * 1 = check failed
         * 2 = check timeout
         * -1 = could not run check */
        public int runCheck()
        {
            string serverAddress = optStrServerAddress;
            int port = optPort;
            string mode = optStrMode;
            string checkString = optStrCheck;
            int result = 0;
            int timeout = optTimeout; /* ms */
            Byte[] sendBytes = new Byte[1024];
            int c = 0, i = 0;
            bool firstRemoteClose = true;

            // convert $xx chars to byte representation
            for (i=0, c=0; i < optStrSendBeforeCheck.Length; i++)
            {
                if (optStrSendBeforeCheck[i] == '$')
                {
                    i++;
                    if (optStrSendBeforeCheck[i] == '$') sendBytes[c++] = (byte)'$';
                    else
                    {
                        string str = optStrSendBeforeCheck.Substring(i, 2);
                        i++;
                        sendBytes[c++] = (byte) Convert.ToByte(str, 16);
                    }
                }
                else sendBytes[c++] = (byte) optStrSendBeforeCheck[i];
            }

            Console.WriteLine ("NetCheckPlugin RunCheck with Instance: " + this.Instance.ToString ());
            beginRunCheck:
            try {
                // reset all wait events

                messageSent.Reset();
                messageReceive.Reset();
                messageTCPConnect.Reset();
                messageReceivedData = "";

                checkRunning = 1;

                if (mode == "UDP") {
                    IPEndPoint RemoteIpEndPoint = new IPEndPoint (IPAddress.Any, 0);
                    UdpClient client = new UdpClient (RemoteIpEndPoint);
                    UdpState state = new UdpState ();
                    state.e = RemoteIpEndPoint;
                    state.u = client;

                    client.BeginSend (sendBytes, c, serverAddress, port, new AsyncCallback (UDPSendCallback), client);
                    if(!messageSent.WaitOne(timeout)) {
                        Console.WriteLine ("UDP: Failed to send message");
                        result = 2;
                        goto runCheckEnd;
                    }
                    client.BeginReceive (new AsyncCallback (UDPReceiveCallback), state);
                    if(!messageReceive.WaitOne(timeout)) {
                        Console.WriteLine ("UDP: Failed to receive message");
                        result = 2;
                        goto runCheckEnd;
                    }
                }
                else if(mode == "TCP") {
                    Socket client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                    client.BeginConnect(serverAddress, port, new AsyncCallback(TCPConnectCallback), client);
                    if(!messageTCPConnect.WaitOne(timeout)) {
                        Console.WriteLine ("TCP: Failed to connect");
                        result = 2;
                        goto runCheckEnd;
                    }

                    client.BeginSend(sendBytes, 0, c, 0, new AsyncCallback(TCPSendCallback), client);
                    if(!messageSent.WaitOne(timeout)) {
                        Console.WriteLine ("TCP: Failed to send message");
                        result = 2;
                        goto runCheckEnd;
                    }

                    TcpState state = new TcpState();
                    state.workSocket = client;
                    client.BeginReceive(state.buffer, 0, TcpState.BufferSize, 0, new AsyncCallback(TCPReceiveCallback), state);
                    if(!messageReceive.WaitOne(timeout)) {
                        Console.WriteLine ("TCP: Failed to receive message");
                        result = 2;
                        goto runCheckEnd;
                    }
                    client.Shutdown(SocketShutdown.Both);
                    client.Close();
                }
                else {
                    /* some error occured, either TCP or UDP selected */
                    result = -1;
                }
            } catch (System.Net.Sockets.SocketException e) {
                if ((uint)e.ErrorCode == 0x80004005 && firstRemoteClose == true)
                {
//.........这里部分代码省略.........
开发者ID:paperwork,项目名称:sourceremotecontrol,代码行数:101,代码来源:PluginCheckNet.cs


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