Visual Studio | WPF > UDPsender (UDP送信と応答受信) > v0.1

```txt:動作環境
Windows 8.1 Pro (64bit)
Microsoft Visual Studio 2017 Community
Sublime Text 2
```

UDPで送信して応答を受信する実装をしてみた。

### 参考

- [2年前に実装したUnityソフト: unity-151117-linemonitor-UI のUDP送信処理](https://github.com/yasokada/unity-151117-linemonitor-UI/blob/master/Assets/SettingSend.cs)
- [Visual Studio | WPF > UDP > echo server > v0.1](https://qiita.com/7of9/items/dc3cb128bcc2766cdf78)
    - 受信処理の参考
    
### code v0.1

```MainWindow.xaml
<Window x:Class="WPF_TCPClient_171205.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:WPF_TCPClient_171205"
        mc:Ignorable="d"
        Title="MainWindow" Height="350" Width="525">
    <Grid Background="LightGray">
        <Button Name="B_send" Content="Send" HorizontalAlignment="Left" Margin="432,67,0,0" 
                VerticalAlignment="Top" Width="75" Click="B_send_Click"/>
        <Label Content="Text" HorizontalAlignment="Left" Margin="10,64,0,0" VerticalAlignment="Top"/>
        <TextBox Name="T_sendText" HorizontalAlignment="Left" Height="23" Margin="58,65,0,0" 
                 TextWrapping="Wrap" Text="Hello" VerticalAlignment="Top" Width="357"/>
        <TextBox Name="T_log" HorizontalAlignment="Left" Height="215" Margin="10,94,0,0" 
                 TextWrapping="Wrap" VerticalAlignment="Top" Width="497"
                 VerticalScrollBarVisibility="Visible"
                 Text="{Binding LogText}"/>
        <Label Content="SendTo" HorizontalAlignment="Left" Margin="10,9,0,0" VerticalAlignment="Top"/>
        <TextBox Name="T_sendTo" HorizontalAlignment="Left" Height="23" Margin="68,10,0,0" 
                 TextWrapping="Wrap" Text="192.168.0.79" VerticalAlignment="Top" Width="120"/>
        <Label Content="port" HorizontalAlignment="Left" Margin="229,9,0,0" VerticalAlignment="Top"/>
        <TextBox Name="T_port" HorizontalAlignment="Left" Height="23" Margin="268,10,0,0" 
                 TextWrapping="Wrap" Text="7000" VerticalAlignment="Top" Width="120"/>

    </Grid>
</Window>
```

```MainWindow.xaml.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
//以下を追加した
using System.Net;
using System.Net.Sockets;
//using System.Text.RegularExpressions;
using System.Threading;
using System.ComponentModel;

namespace WPF_TCPClient_171205
{
    /// <summary>
    /// MainWindow.xaml の相互作用ロジック
    /// </summary>
    public partial class MainWindow : Window, INotifyPropertyChanged
    {
        static private UdpClient s_udpClient;
        static private Thread s_recvThr;
        static private string _logText = string.Empty;

        public MainWindow()
        {
            InitializeComponent();
            UDP_init();

            this.DataContext = this;
        }

        private void UDP_init()
        {
            s_udpClient = new UdpClient();
            s_udpClient.Client.ReceiveTimeout = 300; // msec
            s_udpClient.Client.Blocking = false;

            s_recvThr = new Thread(new ThreadStart(FuncReceiveData));
            s_recvThr.Start();
        }

        public event PropertyChangedEventHandler PropertyChanged;
        protected virtual void OnPropertyChanged(string propertyName = null)
        {
            if (PropertyChanged != null)
                PropertyChanged.Invoke(this, new PropertyChangedEventArgs(propertyName));
        }

        public string LogText
        {
            get { return _logText; }
            set
            {
                _logText = value;
                OnPropertyChanged("LogText");
            }
        }


        private void UDP_send(string ipadr, string portStr, string text)
        {
            if (int.TryParse(portStr, out int portInt) == false)
            {
                return; // error
            }
            byte[] data = Encoding.ASCII.GetBytes(text);
            s_udpClient.Send(data, data.Length, ipadr, portInt);
        }

        private void B_send_Click(object sender, RoutedEventArgs e)
        {
            UDP_send(T_sendTo.Text, T_port.Text, T_sendText.Text);
        }

        private void FuncReceiveData()
        {
            while(true)
            {
                try
                {
                    IPEndPoint anyIP = new IPEndPoint(IPAddress.Any, 0);
                    byte[] data = s_udpClient.Receive(ref anyIP);
                    string text = Encoding.ASCII.GetString(data);

                    if (LogText != null && LogText.Length > 0)
                    {
                        LogText += System.Environment.NewLine;
                    }
                    LogText += text;
                    //
                    Console.WriteLine(text);
                }
                catch(Exception err)
                {
                    // TODO: error処理
                }
            }
        }
    }
}
```

### 実行例

相手側にてecho serverを実行して応答可能状態にしておく。
[Visual Studio | WPF > UDP > echo server > v0.1](https://qiita.com/7of9/items/dc3cb128bcc2766cdf78)

上記の実装ソフトを実行して、送信した例を以下に示す。

![qiita.png](https://qiita-image-store.s3.amazonaws.com/0/32870/b2b016d0-9bea-de13-7bf3-19e9a26a0878.png)

コントロールの配置はXAML直書きではなくGUIで行った。
デザイン時で右と左のマージンを調整していたが、実行時で右側の幅がおかしくなった。