UDPでデータの送受信を行う方法
【データ受信方法】
VB.NET
Public Class UdpReceiver
Public Shared Sub Main()
Dim localIpString As String = "127.0.0.1"
Dim localAddress As System.Net.IPAddress = _
System.Net.IPAddress.Parse(localIpString)
Dim localPort As Integer = 8001
Dim localEP As New System.Net.IPEndPoint(localAddress, localPort)
Dim udp As New System.Net.Sockets.UdpClient(localEP)
While True
Dim remoteEP As System.Net.IPEndPoint = Nothing
Dim rcvBytes As Byte() = udp.Receive(remoteEP)
Dim rcvMsg As String = System.Text.Encoding.UTF8.GetString(rcvBytes)
Console.WriteLine("受信したデータ:{0}", rcvMsg)
Console.WriteLine("送信元アドレス:{0}/ポート番号:{1}", _
remoteEP.Address, remoteEP.Port)
If rcvMsg.Equals("exit") Then
Exit While
End If
End While
udp.Close()
Console.WriteLine("終了しました。")
Console.ReadLine()
End Sub
End Class
作って覚えるVisual C# 2013 デスクトップアプリ入門
C#
using System;
public class UdpReceiver
{
static void Main()
{
string localIpString = "127.0.0.1";
System.Net.IPAddress localAddress =
System.Net.IPAddress.Parse(localIpString);
int localPort = 8001;
System.Net.IPEndPoint localEP =
new System.Net.IPEndPoint(localAddress, localPort);
System.Net.Sockets.UdpClient udp =
new System.Net.Sockets.UdpClient(localEP);
for (; ; )
{
System.Net.IPEndPoint remoteEP = null;
byte[] rcvBytes = udp.Receive(ref remoteEP);
string rcvMsg = System.Text.Encoding.UTF8.GetString(rcvBytes);
Console.WriteLine("受信したデータ:{0}", rcvMsg);
Console.WriteLine("送信元アドレス:{0}/ポート番号:{1}",
remoteEP.Address, remoteEP.Port);
if (rcvMsg.Equals("exit"))
{
break;
}
}
udp.Close();
Console.WriteLine("終了しました。");
Console.ReadLine();
}
}
作って覚えるVisual C# 2013 デスクトップアプリ入門