BeginSend() публичный Метод

public BeginSend ( byte datagram, int bytes, AsyncCallback requestCallback, object state ) : IAsyncResult
datagram byte
bytes int
requestCallback AsyncCallback
state object
Результат IAsyncResult
        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;
        }
Пример #2
1
	    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);
	
	        }
	    }
Пример #3
0
 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;
 }
Пример #4
0
 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;
 }
Пример #5
0
 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;
 }
Пример #6
0
 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);            
 }
Пример #7
0
        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");
        }
Пример #8
0
        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);
            });
        }
Пример #9
0
        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);
            });
        }
Пример #10
0
        ///// <summary>
        ///// UDP异步开始发送
        ///// </summary>
        ///// <param name="packData">数据信息</param>
        ///// <param name="length">数据长度</param>
        //public void AddSendMsg(byte[] packData, int length)
        //{
        //    try
        //    {
        //        udpSend.BeginSend(packData, length, readCallback, udpSendState);
        //    }
        //    catch
        //    {
        //    }
        //}
        #endregion
        #region UDP异步开始发送
        /// <summary>
        /// UDP异步开始发送
        /// </summary>
        /// <param name="vMsg">数据信息</param>
        public IMsg SendStart(IMsg vMsg)
        {
            try
            {
                if (vMsg.Length <= 0)
                {
                    return(vMsg.SetResVal(MsgEnu.SendNull));
                }

                udpSend.BeginSend(vMsg.Buffer, vMsg.Length, readCallback, udpSendState);
                return(vMsg);
            }
            catch
            {
            }
            return(new MsgError(MsgEnu.ErrSendFail));
        }
Пример #11
0
 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.");
 }
Пример #12
0
        /// <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
            {

            }
        }
Пример #13
0
    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.");
    }
Пример #14
0
        private bool SendRaw(byte[] byteData)
        {
            bool success = true;

            try
            {
                clientSend.BeginSend(byteData, byteData.Length, new AsyncCallback(SendCallback), clientSend);
                //
                if (Debug)
                {
                    Console.ForegroundColor = ConsoleColor.Yellow;
                    Console.WriteLine("UDP < " + BitConverter.ToString(byteData));
                    Console.ForegroundColor = ConsoleColor.White;
                }
            }
            catch (Exception ex)
            {
                success = false;
                Console.WriteLine(ex.ToString());
            }
            return(success);
        }
Пример #15
0
        private void SendPoll(ref bool busy)
        {
            /* 送信状態であればアクティブ状態でスキップ */
//			if ((send_task_ar_ != null) && (!send_task_ar_.IsCompleted)) {
            if (send_task_busy_)
            {
                busy = true;
                return;
            }

            if (debug_flag)
            {
                var i = 0;
            }

            /* 送信ブロック取得 */
            if (send_data_ == null)
            {
                send_data_ = GetSendData();
            }

            /* 送信データが存在しない場合はIDLE状態でスキップ */
            if (send_data_ == null)
            {
                busy = false;
                return;
            }

            /* 送信開始 */
            debug_flag      = true;
            send_task_busy_ = true;
            send_task_ar_   = udp_client_.BeginSend(send_data_, send_data_.Length, remote_ep_, SendTaskComplete, udp_client_);

            /* 送信完了通知(リクエストが完了したときに通知する場合) */
            NotifySendComplete("", local_ep_text_, remote_ep_text_, send_data_);

            busy = true;
        }
Пример #16
0
        /// <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);
        }
Пример #17
0
		public void BeginSendNull ()
		{
			UdpClient client = new UdpClient ();
			client.BeginSend (null, 0, null, null);
			client.Close ();
		}
Пример #18
0
        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();
        }
        /* 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)
                {
                    firstRemoteClose = false;
                    Console.WriteLine("Restart ... because remote close connection");
                    goto beginRunCheck;
                }
                else
                {
                    Console.WriteLine("NetCheck failed: " + e.ToString());
                    result = 1;
                    goto runCheckEnd;
                }
            } catch (Exception e) {
                Console.WriteLine ("NetCheck failed: " + e.ToString ());
                result = 1;
                goto runCheckEnd;
            }

            if (messageReceivedData != checkString) {
                addTextCB("received data (" + messageReceivedData + ") does not match checkstring (" + checkString + ")");
                result = 1;
            }

            runCheckEnd:
            checkRunning = 0;
            return result;
        }
Пример #20
0
        private void SendUdp(Dictionary<string, string> sampledData)
        {
            var host = _config.Server.Host;
            var port = _config.Server.Port;

            UdpClient client;
            
            try
            {
                client = new UdpClient(host, port);
            }
            catch(SocketException e)
            {
                /*
                 * This happened when the host was a fully qualified domain name that pointed back to the same local sever
                 * and the Internet connection went down. Wrap some clearer messaging around it.    
                 
                   System.Net.Sockets.SocketException (0x80004005): The requested name is valid, but no data of the requested type was found
                   at System.Net.Dns.GetAddrInfo(String name)
                   at System.Net.Dns.InternalGetHostByName(String hostName, Boolean includeIPv6)
                   at System.Net.Dns.GetHostAddresses(String hostNameOrAddress)
                   at System.Net.Sockets.UdpClient.Connect(String hostname, Int32 port)
                   at System.Net.Sockets.UdpClient..ctor(String hostname, Int32 port)
                 */
                string message = string.Format("NStatsD failed to transmit to '{0}:{1}' ({2})", host, port, e.Message);
                LogWarn(message);

                // Typically wouldn't want the code to throw an exception up the chain just because of a failing stat
                #if DEBUG
                    throw new ApplicationException("Thowing Exception due to DEBUG compile: " + message, e);
                #endif

                // Abort sending the data since the connection failed.
                return;
            }

            foreach (var stat in sampledData.Keys)
            {
                var encoding = new ASCIIEncoding();
                var stringToSend = string.Format("{0}:{1}", stat, sampledData[stat]);
                var sendData = encoding.GetBytes(stringToSend);
                LogVerbose("NStatsD sending {0}", stringToSend);
                client.BeginSend(sendData, sendData.Length, UdpClientCallback, client);
            }
        }
 public void UpdateTransfer()
 {
     try
     {
         string strdata = null;
         lock (this.transfer)
         {
             strdata = String.Format("{0}:{1}:{2}", this.config.server_port, this.transfer.transfer_upload, this.transfer.transfer_download);
         }
         IPAddress ipaddress = IPAddress.Parse("127.0.0.1");
         IPEndPoint remoteIpEndPoint = new IPEndPoint(ipaddress, 4001);
         UdpClient udpClient = new UdpClient();
         udpClient.Connect(remoteIpEndPoint);
         byte[] data = Encoding.ASCII.GetBytes(strdata);
         udpClient.BeginSend(data, data.Length, new AsyncCallback(UpdateTransferSendCallback), udpClient);
     }
     catch (Exception)
     {
         //Console.WriteLine(e.ToString());
     }
 }
Пример #22
0
        public void Send(IEnumerable<Messages.MessageBase> messages, IPEndPoint endpoint)
        {
            UdpClient client = new UdpClient();

            byte[] buffer = null;

            foreach (var item in messages)
            {
                item.Host = DiscoveryAddress.ToString();
                item.Port = Port;

                buffer = item.ToArray();
                for (int i = 0; i < MessageCount; i++)
                {
                    client.BeginSend(buffer, buffer.Length, endpoint, delegate(IAsyncResult ar)
                    {
                        var u = (UdpState)ar.AsyncState;
                        u.Client.EndSend(ar);
                        if (u.Counter == MessageCount)
                            u.Client.Close();
                    }, new UdpState(client, i));
                }
            }
        }
Пример #23
0
        /// <summary>
        /// Find a host
        /// </summary>
        /// <param name="o">(dificult multithread shizzle)</param>
        private void findHost(object o)
        {
            try
            {
                IPAddress sub = HelperFunctions.GetSubnet();
                var hostEntry = Dns.GetHostEntry(Dns.GetHostName());

                IPAddress ip = (
               from addr in hostEntry.AddressList
               where addr.AddressFamily == AddressFamily.InterNetwork && addr.GetAddressBytes()[0] == 169
               select addr
                    ).FirstOrDefault();
                Console.WriteLine(ip.ToString());
                byte[] subs = sub.GetAddressBytes();
                byte bb0 = 1;
                byte bb1 = 1;

                if (subs[0] == 255)
                    bb0 = ip.GetAddressBytes()[0];
                if (subs[1] == 255)
                    bb1 = ip.GetAddressBytes()[1];

                if (sub != null)
                {
                    for (byte b0 = bb0; b0 < bb0+1; b0++)
                    {
                        for (byte b1 = bb1; b1 < bb1+1; b1++)
                        {
                            for (byte b2 = 255; b2 > 0; b2--)
                            {
                                for (byte b3 = 1; b3 < 255; b3++)
                                {
                                    byte[] sen = new byte[4] { b0,b1 , b2, b3 };
                                    UdpClient sender = new UdpClient();
                                    sender.Client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.Broadcast, 1);
                                    sender.Client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.DontRoute, 1);
                                    byte[] b = Encoding.UTF8.GetBytes("attempt connect");
                                    try
                                    {
                                        sender.BeginSend(b, b.Length, new IPEndPoint(new IPAddress(sen), 3030), new AsyncCallback(connectionAttempted), sender);
                                    }
                                    catch
                                    {

                                    }
                                    if (remoteHostFound)
                                        break;
                                }
                                if (remoteHostFound)
                                    break;
                                Console.WriteLine(b2);
                            }

                        }
                    }
                }
            }
            catch(Exception ex)
            {

            }
        }
Пример #24
0
        private void HandleRequest(UdpClient udpClient, IPEndPoint clientEndpoint, byte[] requestMetadata)
        {
            // check if request packet is damaged
            var request = DiscoveryMetadataHelper.Decode(requestMetadata);
            if (request == null)
            {
                return;
            }

            // make sure discovery metadata matches the request
            if (!ResponseMetadata.Matches(request) || Stopped)
            {
                return;
            }

            // send a response
            SafePerform(() =>
            {
                udpClient.BeginSend(ResponseMetadataPacket, ResponseMetadataPacket.Length, clientEndpoint, SendCallback, udpClient);
            });
        }
Пример #25
0
		private void SendPacket(UdpClient Client, IPEndPoint Destination, byte[] Packet)
		{
			Client.BeginSend(Packet, Packet.Length, Destination, this.EndSend, Client);
		}
Пример #26
0
		public void BeginSend ()
		{
			UdpClient client = new UdpClient ();
			byte[] bytes = new byte[] {10, 11, 12, 13};

			try {
				client.BeginSend (bytes, bytes.Length, new AsyncCallback (BSCallback), client);
				Assert.Fail ("BeginSend #1");
			} catch (SocketException ex) {
				Assert.AreEqual (10057, ex.ErrorCode,
						 "BeginSend #2");
			}
			
			try {
				client.BeginSend (bytes, bytes.Length, null, new AsyncCallback (BSCallback), client);
				Assert.Fail ("BeginSend #3");
			} catch (SocketException ex) {
				Assert.AreEqual (10057, ex.ErrorCode,
						 "BeginSend #4");
			}

			IPEndPoint ep = new IPEndPoint (Dns.GetHostEntry (string.Empty).AddressList[0], 1236);
			
			BSCalledBack.Reset ();
			
			client.BeginSend (bytes, bytes.Length, ep,
					  new AsyncCallback (BSCallback),
					  client);
			if (BSCalledBack.WaitOne (2000, false) == false) {
				Assert.Fail ("BeginSend wait timed out");
			}
			
			Assert.AreEqual (true, BSSent, "BeginSend #5");
			Assert.AreEqual (4, BSBytes, "BeginSend #6");

			client.Close ();
		}
Пример #27
0
        private void Send(Dictionary<string, string> data, double sampleRate = 1)
        {
            if (Config == null)
            {
              return;
            }

            Dictionary<string, string> sampledData;
            if (sampleRate < 1 && _random.Next(0, 1) <= sampleRate)
            {
                sampledData = new Dictionary<string, string>();
                foreach (var stat in data.Keys)
                {
                    sampledData.Add(stat, string.Format("{0}|@{1}", data[stat], sampleRate));
                }
            }
            else
            {
                sampledData = data;
            }

            var host = Config.Server.Host;
            var port = Config.Server.Port;
            using (var client = new UdpClient(host, port))
            {
                foreach (var stat in sampledData.Keys)
                {
                    var encoding = new System.Text.ASCIIEncoding();
                    var stringToSend = string.Format("{0}:{1}", stat, sampledData[stat]);
                    var sendData = encoding.GetBytes(stringToSend);
                    client.BeginSend(sendData, sendData.Length, Callback, null);
                }
            }
        }