■■■

2016年4月5日火曜日

UDPデータ送受信で画面が固まらないように非同期送受信する方法

Simply Programming C# and Visual Basic: C# and Visual Basic

UDPデータ送受信で画面が固まらないように非同期送受信する方法

VB.NET
Private udpClient As System.Net.Sockets.UdpClient = Nothing

Private Sub Form1_Load(sender As Object, e As EventArgs) _
        Handles MyBase.Load
    btn1.Text = "受信"
    btn2.Text = "送信"
End Sub

Private Sub btn1_Click(sender As Object, e As EventArgs) _
        Handles btn1.Click
    If udpClient IsNot Nothing Then
        Return
    End If
    DirectCast(sender, Button).Enabled = False

    Dim localEP As New System.Net.IPEndPoint( _
        System.Net.IPAddress.Any, Integer.Parse(TextBox1.Text))
    udpClient = New System.Net.Sockets.UdpClient(localEP)
    udpClient.BeginReceive(AddressOf ReceiveCallback, udpClient)
End Sub

Private Sub ReceiveCallback(ar As IAsyncResult)
    Dim udp As System.Net.Sockets.UdpClient = _
        DirectCast(ar.AsyncState, System.Net.Sockets.UdpClient)

    Dim remoteEP As System.Net.IPEndPoint = Nothing
    Dim rcvBytes As Byte()
    Try
        rcvBytes = udp.EndReceive(ar, remoteEP)
    Catch ex As System.Net.Sockets.SocketException
        Console.WriteLine("受信エラー({0}/{1})", ex.Message, ex.ErrorCode)
        Return
    Catch ex As ObjectDisposedException
        Console.WriteLine("Socketは閉じられています。")
        Return
    End Try

    Dim rcvMsg As String = System.Text.Encoding.UTF8.GetString(rcvBytes)

    Dim displayMsg As String = String.Format("[{0} ({1})] > {2}", _
        remoteEP.Address, remoteEP.Port, rcvMsg)
    RichTextBox1.BeginInvoke( _
        New Action(Of String)(AddressOf ShowReceivedString), displayMsg)

    udp.BeginReceive(AddressOf ReceiveCallback, udp)
End Sub

Private Sub ShowReceivedString(str As String)
    RichTextBox1.Text = str & vbCrLf & RichTextBox1.Text
End Sub

Private Sub btn2_Click(sender As Object, e As EventArgs) _
        Handles btn2.Click
    btn1.Enabled = False

    Dim sendBytes As Byte() = _
        System.Text.Encoding.UTF8.GetBytes(TextBox4.Text)

    If udpClient Is Nothing Then
        udpClient = New System.Net.Sockets.UdpClient()
    End If

   udpClient.BeginSend(sendBytes, sendBytes.Length, TextBox2.Text, _
        Integer.Parse(TextBox3.Text), AddressOf SendCallback, udpClient)
End Sub

Private Sub SendCallback(ar As IAsyncResult)
    Dim udp As System.Net.Sockets.UdpClient = _
        DirectCast(ar.AsyncState, System.Net.Sockets.UdpClient)

    Try
        udp.EndSend(ar)
    Catch ex As System.Net.Sockets.SocketException
        Console.WriteLine("送信エラー({0}/{1})", ex.Message, ex.ErrorCode)
    Catch ex As ObjectDisposedException
        Console.WriteLine("Socketは閉じられています。")
    End Try
End Sub

Private Sub Form1_FormClosed(sender As Object, e As FormClosedEventArgs) _
        Handles MyBase.FormClosed
    If udpClient IsNot Nothing Then
        udpClient.Close()
    End If
End Sub

Simply Programming C# and Visual Basic: C# and Visual Basic

C#
private System.Net.Sockets.UdpClient udpClient = null;

private void Form1_Load(object sender, EventArgs e)
{
    btn1.Text = "受信";
    btn2.Text = "送信";
}

private void btn1_Click(object sender, EventArgs e)
{
    if (udpClient != null)
    {
        return;
    }
    ((Button)sender).Enabled = false;

    System.Net.IPEndPoint localEP = new System.Net.IPEndPoint(
        System.Net.IPAddress.Any, int.Parse(TextBox1.Text));
    udpClient = new System.Net.Sockets.UdpClient(localEP);
    udpClient.BeginReceive(ReceiveCallback, udpClient);
}

private void ReceiveCallback(IAsyncResult ar)
{
    System.Net.Sockets.UdpClient udp =
        (System.Net.Sockets.UdpClient)ar.AsyncState;

    System.Net.IPEndPoint remoteEP = null;
    byte[] rcvBytes;
    try
    {
        rcvBytes = udp.EndReceive(ar, ref remoteEP);
    }
    catch(System.Net.Sockets.SocketException ex)
    {
        Console.WriteLine("受信エラー({0}/{1})",
            ex.Message, ex.ErrorCode);
        return;
    }
    catch (ObjectDisposedException ex)
    {
        Console.WriteLine("Socketは閉じられています。");
        return;
    }

    string rcvMsg = System.Text.Encoding.UTF8.GetString(rcvBytes);

    string displayMsg=string.Format("[{0} ({1})] > {2}",
        remoteEP.Address, remoteEP.Port, rcvMsg);
    RichTextBox1.BeginInvoke(
        new Action<string>(ShowReceivedString), displayMsg);

    udp.BeginReceive(ReceiveCallback, udp);
}

private void ShowReceivedString(string str)
{
    RichTextBox1.Text = str + "\r\n" + RichTextBox1.Text;
}

private void btn2_Click(object sender, EventArgs e)
{
    btn1.Enabled = false;

    byte[] sendBytes =
        System.Text.Encoding.UTF8.GetBytes(TextBox4.Text);

    if (udpClient == null)
    {
        udpClient = new System.Net.Sockets.UdpClient();
    }

    udpClient.BeginSend(sendBytes, sendBytes.Length,
        TextBox2.Text, int.Parse(TextBox3.Text),
        SendCallback, udpClient);
}

private void SendCallback(IAsyncResult ar)
{
    System.Net.Sockets.UdpClient udp =
        (System.Net.Sockets.UdpClient)ar.AsyncState;

    try
    {
        udp.EndSend(ar);
    }
    catch (System.Net.Sockets.SocketException ex)
    {
        Console.WriteLine("送信エラー({0}/{1})",
            ex.Message, ex.ErrorCode);
    }
    catch (ObjectDisposedException ex)
    {
        Console.WriteLine("Socketは閉じられています。");
    }
}

private void Form1_FormClosed(object sender, FormClosedEventArgs e)
{
    if (udpClient != null)
    {
        udpClient.Close();
    }
}
Simply Programming C# and Visual Basic: C# and Visual Basic
■■■