예제 #1
0
        private static async Task Discover()
        {
            using (var server = new System.Net.Sockets.UdpClient(8888))
            {
                var responseData = System.Text.Encoding.ASCII.GetBytes($"port: {Port}|id: {ServerId:D}");

                while (!_stopping)
                {
                    try
                    {
                        var clientRequestData = await server.ReceiveAsync(); // (ref clientEp);

                        var clientRequest = System.Text.Encoding.ASCII.GetString(clientRequestData.Buffer);
                        if (clientRequest == "sync-service")
                        {
                            Console.WriteLine("Request from {0}, sending discover response", clientRequestData.RemoteEndPoint.Address);
                            await server.SendAsync(responseData, responseData.Length, clientRequestData.RemoteEndPoint);
                        }
                        else
                        {
                            Console.WriteLine("Request from {0} invalid {1}", clientRequestData.RemoteEndPoint.Address, clientRequest);
                            await server.SendAsync(responseData, responseData.Length, clientRequestData.RemoteEndPoint);
                        }
                    }
                    catch (Exception e)
                    {
                        Console.WriteLine($"Failed on discovery: {e}");
                        await Task.Delay(2000);
                    }
                }
            }
        }
예제 #2
0
 /// <summary>Sends a UDP message to the specified IP address and Port.</summary>
 /// <param name="mySendIP">IP address to send the data to.</param>
 /// <param name="myClient">The UDP Client to send to.</param>
 /// <param name="mySendPort">Port to send the data on.</param>
 public async void SendUdp(System.Net.Sockets.UdpClient myClient, System.Net.IPAddress mySendIP, int mySendPort)
 {
     try {
         System.Net.IPEndPoint myEndPoint = new System.Net.IPEndPoint(mySendIP, mySendPort);
         await myClient.SendAsync(Buffer, BytePeek, myEndPoint);
     } catch (System.Exception) {}
 }
 public async Task Write(List <LogEntry> logEntries)
 {
     foreach (var msg in logEntries)
     {
         byte[] sendBytes = System.Text.Encoding.ASCII.GetBytes(msg.Message);
         await _udpClient.SendAsync(sendBytes, sendBytes.Length, _host, _port);
     }
 }
예제 #4
0
        public async Task <int> SendAsync(byte[] data)
        {
            using (var udpClient = new System.Net.Sockets.UdpClient())
            {
                var result = await udpClient.SendAsync(data, data.Length, host, port).ConfigureAwait(false);

                return(result);
            }
        }
예제 #5
0
        private static void Main(string[] args)
        {
            byte[] toDisplay = null;

            var consoleUpdater = Task.Run(async() =>
            {
                while (true)
                {
                    if (toDisplay != null)
                    {
                        Console.SetCursorPosition(0, 0);
                        Console.Write(StatusScreen(toDisplay));
                        toDisplay = null;
                    }

                    await Task.Delay(300);
                }
            });


            var ipEndPoint   = new IPEndPoint(IPAddress.Loopback, FORZA_DATA_OUT_PORT);
            var senderClient = new System.Net.Sockets.UdpClient(FORZA_HOST_PORT);
            var senderTask   = Task.Run(async() =>
            {
                while (true)
                {
                    Console.WriteLine("Sending heartbeat");
                    await senderClient.SendAsync(new byte[1], 1, ipEndPoint);
                    await Task.Delay(5000);
                }
            });

            var receiverTask = Task.Run(async() =>
            {
                Console.Clear();
                var client = new System.Net.Sockets.UdpClient(FORZA_DATA_OUT_PORT);
                Console.WriteLine("Listening... ");
                while (true)
                {
                    await client.ReceiveAsync().ContinueWith(receive =>
                    {
                        var resultBuffer = receive.Result.Buffer;
                        if (resultBuffer.Length != 311 || toDisplay != null)
                        {
                            return;
                        }

                        var stuff = new byte[resultBuffer.Length];
                        resultBuffer.CopyTo(stuff, 0);
                        toDisplay = stuff;
                    });
                }
            });


            Task.WaitAll(senderTask, receiverTask, consoleUpdater);
        }
예제 #6
0
        public ReplyData GetReply(InputData data)
        {
            byte[] inputBuffer = ByteArray.CreateFrom(data);
            server.SendAsync(inputBuffer, inputBuffer.Length, destination).Wait();

            var message   = replySocket.ReceiveAsync().Result.Buffer;
            var replyData = message.ConvertTo <ReplyData>();

            return(replyData);
        }
예제 #7
0
 public async Task SendAsync(byte[] data, int index, int count)
 {
     if (index != 0) //Should never happen?
     {
         var newData = new byte[count];
         Buffer.BlockCopy(data, index, newData, 0, count);
         data = newData;
     }
     await _udp.SendAsync(data, count, _destination).ConfigureAwait(false);
 }
예제 #8
0
 public Task <int> WriteAsync(byte[] buffer, int start, int length)
 {
     return(_udpClient.SendAsync(buffer, buffer.Length, _serverEndPoint));
 }
예제 #9
0
        static void Main(string[] args)
        {
            //接続先のIPアドレスを入力
            Console.Write("接続先IPアドレス:");
            string remoteHost = Console.ReadLine();

            //String型のIPアドレスをIPAddress型にParse
            IPAddress remoteAddress;

            if (IPAddress.TryParse(remoteHost, out remoteAddress) == false)
            {
                Console.WriteLine("正しくないIPアドレスが入力されました");

                // 終了
                Environment.Exit(-1);
            }

            //IPエンドポイントを生成
            var remoteEndPoint = new IPEndPoint(remoteAddress, remotePort);
            var localEndPoint  = new IPEndPoint(IPAddress.Any, localPort);

            //UdpClientオブジェクトを生成
            var udp = new System.Net.Sockets.UdpClient(localEndPoint);

            using (var waveIn = new WaveInEvent())
            {
                //総送信バイト数を保持する変数
                long count = 0;

                //入力バッファのサイズを設定(20ms)
                waveIn.BufferMilliseconds = 20;

                //G.722コーデックを用意
                var codec      = new NAudio.Codecs.G722Codec();
                var codecState = new NAudio.Codecs.G722CodecState(64000, NAudio.Codecs.G722Flags.None);

                //音声データ利用可能時の処理(非同期)
                waveIn.DataAvailable += async(_, e) =>
                {
                    //-- 送信処理 --
                    byte[] bufferedBytes = new byte[e.BytesRecorded];
                    Array.Copy(e.Buffer, bufferedBytes, e.BytesRecorded);

                    short[] bufferedData  = Convert16BitToShort(bufferedBytes);
                    byte[]  encodedBytes  = new byte[e.BytesRecorded];
                    int     encodedLength = codec.Encode(codecState, encodedBytes, bufferedData, bufferedData.Length);

                    byte[] bufferToSend = new byte[bufsize];

                    for (int i = 0; i < encodedLength; i += bufsize)
                    {
                        if (encodedLength > i + bufsize)
                        {
                            //バッファ内のデータがペイロードサイズ以上
                            Array.Copy(encodedBytes, i, bufferToSend, 0, bufsize);
                            await udp.SendAsync(bufferToSend, bufferToSend.Length, remoteEndPoint);
                        }
                        else
                        {
                            //バッファ内のサイズがペイロードサイズ以下
                            Array.Copy(encodedBytes, i, bufferToSend, 0, encodedLength - i);
                            await udp.SendAsync(bufferToSend, encodedLength - i, remoteEndPoint);
                        }
                    }

                    count += encodedLength;
                    Console.WriteLine(count);

                    await Task.Delay(10);
                };

                //入力フォーマット設定(16kHz, 16bit, 1ch)
                waveIn.WaveFormat = new WaveFormat(16000, 16, 1);

                //音声の取得開始
                waveIn.StartRecording();

                Console.WriteLine("Press ENTER to quit...");
                Console.ReadLine();

                //音声の取得終了
                waveIn.StopRecording();
            }

            udp.Close();

            Console.WriteLine("Program ended successfully.");
        }
예제 #10
0
        /// <summary>
        /// UDP音声パケットの送信を開始します
        /// </summary>
        /// <param name="remoteAddress">リモートIPアドレス</param>
        /// <param name="cancellTokenSource">受信を停止するためのCancellationTokenSource</param>
        /// <returns></returns>
        public async Task StartSendAsync(IPAddress remoteAddress, CancellationTokenSource cancellTokenSource)
        {
            //IPエンドポイントを生成
            var remoteEndPoint = new IPEndPoint(remoteAddress, RemotePort);
            var localEndPoint  = new IPEndPoint(IPAddress.Any, LocalPort);

            //UdpClientオブジェクトを生成
            var udp = new System.Net.Sockets.UdpClient(localEndPoint);

            using (var waveIn = new WaveInEvent())
            {
                //入力バッファのサイズを設定(20ms)
                waveIn.BufferMilliseconds = 20;

                //G.722コーデックを用意
                var codec      = new NAudio.Codecs.G722Codec();
                var codecState = new NAudio.Codecs.G722CodecState(64000, NAudio.Codecs.G722Flags.None);

                //音声データ利用可能時の処理(非同期)
                waveIn.DataAvailable += async(_, e) =>
                {
                    //-- 送信処理 --
                    byte[] bufferedBytes = new byte[e.BytesRecorded];
                    Array.Copy(e.Buffer, bufferedBytes, e.BytesRecorded);

                    short[] bufferedData  = Convert16BitToShort(bufferedBytes);
                    byte[]  encodedBytes  = new byte[e.BytesRecorded];
                    int     encodedLength = codec.Encode(codecState, encodedBytes, bufferedData, bufferedData.Length);

                    byte[] bufferToSend = new byte[MaxPacketPayloadSize];

                    for (int i = 0; i < encodedLength; i += MaxPacketPayloadSize)
                    {
                        if (encodedLength > i + MaxPacketPayloadSize)
                        {
                            //バッファ内のデータがペイロードサイズ以上
                            Array.Copy(encodedBytes, i, bufferToSend, 0, MaxPacketPayloadSize);
                            await udp.SendAsync(bufferToSend, bufferToSend.Length, remoteEndPoint);
                        }
                        else
                        {
                            //バッファ内のサイズがペイロードサイズ以下
                            Array.Copy(encodedBytes, i, bufferToSend, 0, encodedLength - i);
                            await udp.SendAsync(bufferToSend, encodedLength - i, remoteEndPoint);
                        }
                    }
                    await Task.Delay(10);
                };

                //入力フォーマット設定(16kHz, 16bit, 1ch)
                waveIn.WaveFormat = new WaveFormat(16000, 16, 1);

                //音声の取得開始
                waveIn.StartRecording();

                while (true)
                {
                    if (cancellTokenSource.IsCancellationRequested)
                    {
                        break;
                    }
                    await Task.Delay(100);
                }

                //音声の取得終了
                waveIn.StopRecording();
            }
            udp.Close();
        }
예제 #11
0
 public void Write(string msg)
 {
     byte[] sendBytes = System.Text.Encoding.ASCII.GetBytes(msg);
     _udpClient.SendAsync(sendBytes, sendBytes.Length, _host, _port);
 }