受信側サンプルコード
// 基本
var receiveIpAddress = "127.0.0.1";
var local = new IPEndPoint(IPAddress.Parse(receiveIpAddress), Port);
var remote = new IPEndPoint(IPAddress.Any, 8006) as EndPoint;
socket.Bind(local);
var buffer = new byte[3];
while (true)
{
Console.WriteLine("Start Receiving");
// var length = socket.ReceiveFrom(buffer, ref remote);
var length = socket.Receive(buffer);
var requiredBuffer = new byte[length];
Buffer.BlockCopy(buffer, 0, requiredBuffer, 0, length);
var data = Encoding.UTF8.GetString(requiredBuffer);
Console.WriteLine("data received: " + data);
}
受信側コードの注意点
bufferの配列サイズがdatagramサイズより小さいと、下記のようなエラーが出る
System.Net.Sockets.SocketException (10040): A message sent on a datagram socket was larger than the internal message buffer or some other network limit, or the buffer used to receive a datagram into was smaller than the datagram itself.
コメント