VB.net にて UDP接続

ーーーー送信ーーーー

        Dim udpClient As New System.Net.Sockets.UdpClient()
        udpClient.Connect("localhost", 1000)
        Dim sendBytes As [Byte]() = System.Text.Encoding.Default.GetBytes("送信文字列")
        udpClient.Send(sendBytes, sendBytes.Length)
        udpClient.Close()

ーーーー受信ーーーー

        Dim receivingUdpClient As New System.Net.Sockets.UdpClient(1000) '受信するポート番号
        Dim RemoteIpEndPoint As New System.Net.IPEndPoint(System.Net.IPAddress.Any, 0)
        Try
            Dim receiveBytes As [Byte]() = receivingUdpClient.Receive(RemoteIpEndPoint)
            '↑受信するまでこの行でとまっています。
            Dim returnData As String = System.Text.Encoding.Default.GetString(receiveBytes)
            Console.WriteLine(returnData)
            'RemoteIpEndPoint.Address.ToString() '送信側のアドレスが格納されてます
            'RemoteIpEndPoint.Port.ToString() '送信側のポート番号が格納されてます
        Catch e As Exception
            Console.WriteLine(e.ToString())
        End Try

ーーーーGUIアプリケーションでの受信操作ーーーー

    Dim threads1 As New System.Threading.Thread(AddressOf Receive)
    Dim receivingUdpClient As New System.Net.Sockets.UdpClient(1000) '受信するポート番号
    Dim RemoteIpEndPoint As New System.Net.IPEndPoint(System.Net.IPAddress.Any, 0)
    Dim str As String = ""
    Dim LoopFlag As Boolean = True

    Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        threads1.Start()
    End Sub

    Private Sub Timer1_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Timer1.Tick
        Timer1.Enabled = False
        TextBox2.Text = str
        Timer1.Enabled = True
    End Sub

    Private Sub Receive()
        Do
            Try
                Dim receiveBytes As [Byte]() = receivingUdpClient.Receive(RemoteIpEndPoint)
                '↑受信するまでこの行でとまっています。
                Dim returnData As String = System.Text.Encoding.Default.GetString(receiveBytes)
                Console.WriteLine(returnData)
                str = returnData
                'RemoteIpEndPoint.Address.ToString() '送信側のアドレスが格納されてます
                'RemoteIpEndPoint.Port.ToString() '送信側のポート番号が格納されてます
            Catch err As Exception
                Console.WriteLine(err.ToString())
            End Try
        Loop While (LoopFlag)
    End Sub



▲トップページ > Visual BASIC と C#