Esempio n. 1
0
        public void Send(byte[] data, AsyncCallback callback = null)
        {
            if (data == null || data.Length == 0)
            {
                return;
            }

            try {
                sender?.BeginSend(data, data.Length, callback, sender);
            } catch (Exception e) {
                Close(e.Message);
            }
        }
 /// <summary>
 ///     Sends data to the client via UDP.
 /// </summary>
 public void SendData(Packet packet)
 {
     if (packet != null)
     {
         _udpClient?.BeginSend(packet.ToArray(), packet.Length, null, null);
     }
 }
Esempio n. 3
0
        public void BeginSend_AsyncOperationCompletes_Success()
        {
            UdpClient udpClient = new UdpClient();
            byte[] sendBytes = new byte[1];
            IPEndPoint remoteServer = new IPEndPoint(IPAddress.Loopback, UnusedPort);
            _waitHandle.Reset();
            udpClient.BeginSend(sendBytes, sendBytes.Length, remoteServer, new AsyncCallback(AsyncCompleted), udpClient);

            Assert.True(_waitHandle.WaitOne(Configuration.PassingTestTimeout), "Timed out while waiting for connection");
        }
Esempio n. 4
0
        public void BeginSend_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");
        }
Esempio n. 5
0
        public void BeginSend_BytesMoreThanArrayLength_Throws()
        {
            UdpClient udpClient = new UdpClient(AddressFamily.InterNetwork);
            byte[] sendBytes = new byte[1];
            IPEndPoint remoteServer = new IPEndPoint(IPAddress.Loopback, UnusedPort);

            Assert.Throws<ArgumentOutOfRangeException>("bytes", () =>
            {
                udpClient.BeginSend(sendBytes, sendBytes.Length + 1, remoteServer, new AsyncCallback(AsyncCompleted), udpClient);
            });
        }
Esempio n. 6
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);
            });
        }
Esempio n. 7
0
 /// <summary>Sends data to the client via UDP.</summary>
 /// <param name="_packet">The packet to send.</param>
 public void SendData(Packet _packet)
 {
     try
     {
         _packet.InsertInt(instance.myId); // Insert the client's ID at the start of the packet
         socket?.BeginSend(_packet.ToArray(), _packet.Length(), null, null);
     }
     catch (Exception _ex)
     {
         Debug.Log($"Error sending data to server via UDP: {_ex}");
     }
 }
Esempio n. 8
0
 public void SendData(Packet packet)
 {
     try
     {
         packet.InsertInt(Instance.Id);
         Socket?.BeginSend(packet.ToArray(), packet.Length(), null, null);
     }
     catch (Exception e)
     {
         Console.WriteLine($"Error sending data to Player {Instance.Id} via Udp: {e}");
     }
 }
Esempio n. 9
0
 public void SendData(Packet packet)
 {
     try
     {
         packet.InsertInt(Instance.myId);
         socket?.BeginSend(packet.ToArray(), packet.Length(), null, null);
     }
     catch (Exception e)
     {
         Debug.Log($"Error sending data to server via UDP: {e}");
     }
 }
        public void SendMessage(string text)
        {
            string outboundMessage = $"Content: {text} \n Sent at: {DateTime.Now}\n Outgoing address: {GetLocalAddress()} \n Target address: {remoteEndpoint}";

            byte[] message = Encoding.ASCII.GetBytes(outboundMessage);
            udpClient.BeginSend(message, message.Length, (ar) =>
            {
                State so  = (State)ar.AsyncState;
                int bytes = udpClient.EndSend(ar);
                Console.WriteLine("-----------------------");
                Console.WriteLine($"SENT: \n {outboundMessage} \n Sent bytes: {bytes} \n");
            }, state);
        }
Esempio n. 11
0
        public void BeginSend_BytesMoreThanArrayLength_Throws()
        {
            using (UdpClient udpClient = new UdpClient(AddressFamily.InterNetwork))
            {
                byte[]     sendBytes    = new byte[1];
                IPEndPoint remoteServer = new IPEndPoint(IPAddress.Loopback, UnusedPort);

                AssertExtensions.Throws <ArgumentOutOfRangeException>("bytes", () =>
                {
                    udpClient.BeginSend(sendBytes, sendBytes.Length + 1, remoteServer, new AsyncCallback(AsyncCompleted), udpClient);
                });
            }
        }
Esempio n. 12
0
 public static void SendUDPData(IPEndPoint clientEndPoint, Packet packet)
 {
     try
     {
         if (clientEndPoint != null)
         {
             udpListener.BeginSend(packet.ToArray(), packet.Length(), clientEndPoint, null, null);
         }
     }
     catch (Exception ex)
     {
         Debug.Log("SendUDPData error: " + ex.Message);
     }
 }
Esempio n. 13
0
 public void SendData(Packet _packet)
 {
     try
     {
         _packet.InsertInt(myId);
         if (socket != null)
         {
             socket.BeginSend(_packet.ToArray(), _packet.Length(), null, null);
         }
     } catch (Exception ex)
     {
         Console.WriteLine($"Error sending data to server via UDP: {ex}");
     }
 }
Esempio n. 14
0
 /// <summary>
 /// 发送数据
 /// </summary>
 /// <param name="msg"></param>
 /// <param name="remote"></param>
 public void Send(string msg, IPEndPoint remote)
 {
     byte[] data = Encoding.Default.GetBytes(msg);
     try
     {
         RaisePrepareSend(null);
         _server.BeginSend(data, data.Length, new AsyncCallback(SendCallback), null);
     }
     catch (Exception)
     {
         //TODO 异常处理
         RaiseOtherException(null);
     }
 }
Esempio n. 15
0
 private void SendStatsAsync(string name, long timestamp, long timeTaken)
 {
     try
     {
         var client = new UdpClient();
         client.Connect(Config.IpAddress, Config.Port);
         var sendBytes = Encoding.ASCII.GetBytes(string.Format("{0}|{1}|{2}", name, timeTaken, timestamp));
         client.BeginSend(sendBytes, sendBytes.Length, OnSend, client);
     }
     catch
     {
         // Suppress exception.
     }
 }
 public static void SendUDPData(IPEndPoint clientEndPoint, Packet packet)
 {
     try
     {
         if (clientEndPoint != null)
         {
             udpListener.BeginSend(packet.ToArray(), packet.Length(), clientEndPoint, null, null);
         }
     }
     catch (Exception ex)
     {
         Debug.LogError($"Error sending data to {clientEndPoint} via UDP : {ex}");
     }
 }
	public static void SendUDPData(IPEndPoint clientEndPoint, Packet packet)
	{
		try
		{
			if (clientEndPoint != null)
			{
				_udpListener.BeginSend(packet.ToArray(), packet.Length(), clientEndPoint, null, null);
			}
		}
		catch (Exception e)
		{
			Console.WriteLine($"[Server] Error sending data to {clientEndPoint} via UPD: {e}");
		}
	}
Esempio n. 18
0
 public static void SendUDPData(IPEndPoint clientEndPoint, Packet packet)
 {
     try
     {
         if (clientEndPoint != null)
         {
             udpListener.BeginSend(packet.ToArray(), packet.Length(), clientEndPoint, null, null);
         }
     }
     catch (Exception e)
     {
         Debug.Log($"Error on sending data to client end point {clientEndPoint}, {e}");
     }
 }
Esempio n. 19
0
 public void SendData(Packet packet)
 {
     try
     {
         packet.InsertInt(instance.myId);
         if (socket != null)
         {
             socket.BeginSend(packet.ToArray(), packet.Length(), null, null);
         }
     }catch (Exception ex)
     {
         Debug.Log(ex.Message);
     }
 }
Esempio n. 20
0
 public void SendData(Packet _packet)
 {
     try
     {
         _packet.InsertInt(instance.myId);
         if (socket != null)
         {
             socket.BeginSend(_packet.ToArray(), _packet.Length(), null, null);
         }
     } catch (Exception _ex)
     {
         Debug.Log($"Error sending data to server via UDP: {_ex}");
     }
 }
Esempio n. 21
0
 public static void SendUDPData(IPEndPoint clientEndPoint, Packet packet)
 {
     try
     {
         if (clientEndPoint != null)
         {
             udpListener.BeginSend(packet.ToArray(), packet.Length(), clientEndPoint, null, null);
         }
     }
     catch (Exception ex)
     {
         Debug.Log($"向{clientEndPoint}发送UDP数据时出错:{ex}");
     }
 }
Esempio n. 22
0
 public static void SendUDPData(IPEndPoint _clientEndPoint, Packet _packet)
 {
     try
     {
         if (_clientEndPoint != null)
         {
             udpListener.BeginSend(_packet.ToArray(), _packet.Length(), _clientEndPoint, null, null);
         }
     }
     catch (Exception _ex)
     {
         Console.WriteLine($"Error sending UDP data: {_ex}");
     }
 }
Esempio n. 23
0
    //发送握手数据 16字节 8字节头+4字节index+4字节key
    private void SendHandshake()
    {
        if (UdpLibConfig.DebugLevel != (int)UdpLibLogLevel.None)
        {
#if DEBUG
            Console.WriteLine("发送握手数据");
#endif
        }

        Interlocked.Increment(ref m_pktCounter);
        byte[] buf = new byte[UdpLibConfig.HandshakeDataSize + 4];
        Array.Copy(UdpLibConfig.HandshakeHeadData, buf, UdpLibConfig.HandshakeHeadData.Length);
        KCP.ikcp_encode32u(buf, UdpLibConfig.HandshakeHeadData.Length, m_NetIndex);
        KCP.ikcp_encode32u(buf, UdpLibConfig.HandshakeHeadData.Length + 4, (uint)m_Key);
        KCP.ikcp_encode32u(buf, UdpLibConfig.HandshakeHeadData.Length + 8, (uint)m_pktCounter);
        //m_UdpClient.Send(buf, buf.Length);
        m_UdpClient.BeginSend(buf, buf.Length, server_addr, (IAsyncResult iar) => { m_UdpClient.EndSend(iar); }, null);
#if DEV
        string s = string.Format("{0},发送握手数据,{1}", m_NetIndex, m_pktCounter.ToString());
        IRQLog.AppLog.Log(s);
        Console.WriteLine(s);
#endif
    }
 public static void WyślijDaneUDP(IPEndPoint _końcowyPunktKlienta, Pakiet _pakiet)
 {
     try
     {
         if (_końcowyPunktKlienta != null)
         {
             nasłuchujUdp.BeginSend(_pakiet.ToArray(), _pakiet.Length(), _końcowyPunktKlienta, null, null);
         }
     }
     catch (Exception _ex)
     {
         Console.WriteLine($"Błąd przesyłu danych do {_końcowyPunktKlienta} po przez UDP: {_ex}");
     }
 }
Esempio n. 25
0
 public static void SendUDPData(IPEndPoint clientEndPoint, Packet packet)
 {
     try
     {
         if (clientEndPoint != null)
         {
             udpClient.BeginSend(packet.ToArray(), packet.Length(), clientEndPoint, null, null);
         }
     }
     catch (Exception ex)
     {
         Console.WriteLine($"Error sending data to {clientEndPoint} via UDP: {ex}");
     }
 }
Esempio n. 26
0
        /// <summary>
        /// Function responsible for sending text messages to called user.
        /// </summary>
        /// <param name="dataPacket">The data packet.</param>
        public void SendMessage(DataPacket dataPacket)
        {
            try
            {
                var dataToSend = dataPacket.PackMessage();

                udpClient.BeginSend(dataToSend, dataToSend.Length, ipEndPoint, null, null);
            }
            catch (Exception ex)
            {
                //TODO Signal error
                MessageBox.Show(ex.ToString());
            }
        }
Esempio n. 27
0
 public static void SendUDPData(IPEndPoint clientEndPoint, Packet packet)
 {
     try
     {
         if (clientEndPoint != null)
         {
             _udpListener.BeginSend(packet.ToArray(), packet.Length(), clientEndPoint, null, null);
         }
     }
     catch (Exception e)
     {
         Chat.Print($"[Server] Error sending data to {clientEndPoint} via UPD: {e}", MessageType.ErrorMessage);
     }
 }
Esempio n. 28
0
 /// <summary>Sends a packet to the specified endpoint via UDP.</summary>
 /// <param name="_clientEndPoint">The endpoint to send the packet to.</param>
 /// <param name="_packet">The packet to send.</param>
 public static void SendUDPData(IPEndPoint _clientEndPoint, Packet _packet)
 {
     try
     {
         if (_clientEndPoint != null)
         {
             udpListener.BeginSend(_packet.ToArray(), _packet.Length(), _clientEndPoint, null, null);
         }
     }
     catch (Exception _ex)
     {
         Debug.Log($"Error sending data to {_clientEndPoint} via UDP: {_ex}");
     }
 }
Esempio n. 29
0
        void audioDataAvailable(object sender, byte[] e)
        {
            MemoryStream ms = new MemoryStream();

            String s = "a000";

            byte[] bufWriter = Encoding.UTF8.GetBytes(s.ToCharArray(), 0, 4);
            ms.Write(bufWriter, 0, 4);

            bufWriter = BitConverter.GetBytes(AudioSessionId);
            if (BitConverter.IsLittleEndian)
            {
                Array.Reverse(bufWriter);
            }
            ms.Write(bufWriter, 0, 4);

            long time = (long)(DateTime.UtcNow - new DateTime(1970, 1, 1)).TotalMilliseconds;

            //Console.WriteLine ((time - lasttime) + " ms delay");
            lasttime  = time;
            bufWriter = BitConverter.GetBytes(time);
            if (BitConverter.IsLittleEndian)
            {
                Array.Reverse(bufWriter);
            }
            ms.Write(bufWriter, 0, 8);

            ms.Write(e, 0, e.Length);

            byte[] sendbuf = ms.ToArray();
            if (sendbuf.Length > 4096)
            {
                throw new Exception("Packet size too large!");
            }
            Task tk = Task.Factory.StartNew(() =>
            {
                try
                {
                    var aSender = audioCaller.BeginSend(sendbuf, sendbuf.Length, null, null);
                    aSender.AsyncWaitHandle.WaitOne(TimeSpan.FromSeconds(3));
                    if (aSender.IsCompleted)
                    {
                        audioCaller.EndSend(aSender);
                    }
                }
                catch
                {
                }
            });
        }
Esempio n. 30
0
        public override void BeginSend(byte[] datagram, int bytes)
        {
            if (udpClient != null)
            {
                udpClient.BeginSend(datagram, bytes, serverIPEndPoint, iar =>
                {
                    UdpClient tcpc;
                    tcpc = (UdpClient)iar.AsyncState;
                    tcpc.EndSend(iar);

                    fireCompleteSend();
                }, udpClient);
            }
        }
Esempio n. 31
0
        void simconnect_OnRecvSimobjectDataBytype(SimConnect sender, SIMCONNECT_RECV_SIMOBJECT_DATA_BYTYPE data)
        {
            switch ((FsDataObjects.DATA_REQUESTS)data.dwRequestID)
            {
            case FsDataObjects.DATA_REQUESTS.REQUEST_1:
                FsDataObjects.AircraftDataStructure acData = (FsDataObjects.AircraftDataStructure)data.dwData[0];

                lblX.Text   = String.Format("{0,0:N5} deg", acData.longitude);
                lblY.Text   = String.Format("{0,0:N5} deg", acData.latitude);
                lblAlt.Text = String.Format("{0,0:N2} ft", acData.altitude);
                lblU.Text   = String.Format("{0,0:N3} ft/s", acData.u);
                lblV.Text   = String.Format("{0,0:N3} ft/s", acData.v);
                lblW.Text   = String.Format("{0,0:N3} ft/s", -acData.w_neg);

                lblYaw.Text   = String.Format("{0,0:N3} deg", acData.yaw);
                lblPitch.Text = String.Format("{0,0:N3} deg", -acData.pitch_neg);
                lblRoll.Text  = String.Format("{0,0:N3} deg", -acData.roll_neg);
                lblP.Text     = String.Format("{0,0:N3} rad/s", -acData.p_neg);
                lblQ.Text     = String.Format("{0,0:N3} rad/s", -acData.q_neg);
                lblR.Text     = String.Format("{0,0:N3} rad/s", acData.r);

                lblMach.Text = String.Format("{0,0:N5}", acData.mach);

                lblElevator.Text = String.Format("{0,0:N3}%", ControlsLatest.elevator * 100);
                lblThrottle.Text = String.Format("{0,0:N3}%", ControlsLatest.throttle1);
                lblAileron.Text  = String.Format("{0,0:N3}%", ControlsLatest.aileron * 100);
                lblRudder.Text   = String.Format("{0,0:N3}%", ControlsLatest.rudder * 100);
                lblGear.Text     = (gear_last == 0) ? "Down" : "Up";
                lblFlaps.Text    = String.Format("{0,0:N0}% Down", (flaps_last / 2.0) * 100.0);
                lblBeta.Text     = String.Format("{0,0:N3} deg", acData.beta * 180.0 / Math.PI);

                String udpSend   = NetworkParser.UdpStringFromAC(acData);
                Byte[] sendBytes = Encoding.ASCII.GetBytes(udpSend);

                DateTime CurrentTime = DateTime.Now;

                if ((CurrentTime - LastSendTime).Milliseconds > 250)
                {
                    udpSendingSocket.BeginSend(sendBytes, sendBytes.Length, endpointSending, null, udpSendingSocket);
                    LastSendTime = DateTime.Now;
                }

                break;

            default:
                WriteToLog("Unknown request ID: " + data.dwRequestID);
                break;
            }
        }
Esempio n. 32
0
        public Task <int> SendAsync(byte[] datagram, int bytes)
        {
            var asyncResult = udpClient.BeginSend(datagram, bytes, null, null);

            asyncResult.AsyncWaitHandle.WaitOne(sendTimeout);
            if (asyncResult.IsCompleted)
            {
                int num = udpClient.EndSend(asyncResult);
                return(Task.FromResult(num));
            }
            else
            {
                throw new TimeoutException();
            }
        }
Esempio n. 33
0
 public static void SendUDPData(IPEndPoint _clientEndPoint, Packet _packet)
 {
     try
     {
         if (_clientEndPoint != null)
         {
             udpListener.BeginSend(_packet.ToArray(), _packet.Length(), _clientEndPoint, null, null);
         }
     }
     catch (Exception e)
     {
         Console.WriteLine($"发送UDP data失败:{e}");
         throw;
     }
 }
Esempio n. 34
0
 /// <summary>Sends data to the client via UDP.</summary>
 /// <param name="packet">The packet to send.</param>
 public void SendData(Packet packet)
 {
     try
     {
         packet.InsertGuid(Get.myId); // Insert the client's ID at the start of the packet
         if (socket != null)
         {
             socket.BeginSend(packet.ToArray(), packet.Length(), null, null);
         }
     }
     catch (Exception ex)
     {
         Debug.Log($"Error sending data to server via UDP: {ex}");
     }
 }
Esempio n. 35
0
    private void RespondClient(IPAddress _ClientAddress, int _ClientPort, byte[] _DataToSend)
    {
        System.Diagnostics.Debug.Assert(m_AdvertisingClientLAN == null);

        IPEndPoint ep2 = new IPEndPoint(_ClientAddress, _ClientPort);
        UdpClient uc2 = new UdpClient();	//@FIXME: doesn't need to pass EndPoint in constructor?
        UdpClientState ucs2 = new UdpClientState(ep2, uc2);
        uc2.BeginSend(_DataToSend, _DataToSend.Length, ep2, new System.AsyncCallback(RespondClientCallback), ucs2);

        m_AdvertisingClientLAN = ucs2;
    }
    private void FindServer(int _ListenPort, int _BroadcastPort)
    {
        System.Diagnostics.Debug.Assert(m_BroadcastClientLAN == null);

        // open a broadcast on known port and
        // send own broadcast listener port to the LAN

        IPEndPoint ep2 = new IPEndPoint(IPAddress.Broadcast, _BroadcastPort);
        UdpClient uc2 = new UdpClient();
        // Important!
        // this is disabled by default
        // so we have to enable it
        uc2.EnableBroadcast = true;

        UdpClientState ucs2 = new UdpClientState(ep2, uc2);

        byte[] sendBytes = System.BitConverter.GetBytes(_ListenPort);
        uc2.BeginSend(sendBytes, sendBytes.Length, ep2, new System.AsyncCallback(FindServerCallback), ucs2);

        m_BroadcastClientLAN = ucs2;

        Debug.Log("Find server message sent on broadcast port " + _BroadcastPort);
    }
Esempio n. 37
0
    public void ListenForClientsCallback(IAsyncResult ar)
    {
        // we received a broadcast from a client

        Debug.Log("Client message received on server listening port");

        UdpClient uc1 = (UdpClient)((UdpState)(ar.AsyncState)).u;
        IPEndPoint ep1 = (IPEndPoint)((UdpState)(ar.AsyncState)).e;
        byte[] receiveBytes = uc1.EndReceive(ar, ref ep1);
        clientPort = BitConverter.ToInt32(receiveBytes,0);

        Debug.Log("Client is listening for reply on broadcast port " + clientPort.ToString());

        // send a response back to the client on the port
        // they sent us

        sentData = multiGameName;
        byte [] sendBytes = Encoding.ASCII.GetBytes(sentData);

        UdpClient uc2 = new UdpClient();
        IPEndPoint ep2 = new IPEndPoint(ep1.Address, clientPort);
        uc2.BeginSend(sendBytes, sendBytes.Length, ep2, new AsyncCallback(RespondClientCallback), uc2);

        // Important!
        // close and re-open the broadcast listening port
        // so that another async operation can start

        uc1.Close();
        Debug.Log("server listening port closed");
        ListenForClients(multiGameName);

        waitingResponse = true;
    }
Esempio n. 38
0
    public void FindServer()
    {
        // open a broadcast on known port 15000 and
        // send own broadcast listener port to the LAN

        UdpClient uc2 = new UdpClient();
        byte [] sendBytes = BitConverter.GetBytes(broadcastEndPoint.Port);

        // Important!
        // this is disabled by default
        // so we have to enable it

        uc2.EnableBroadcast = true;

        IPEndPoint ep2 = new IPEndPoint(IPAddress.Broadcast, 15000);
        uc2.BeginSend(sendBytes, sendBytes.Length, ep2, new AsyncCallback(FindServerCallback), uc2);

        waitingResponse = true;

        Debug.Log("Find server message sent on broadcast listener");
    }