C# と VB.NET の質問掲示板

わんくま同盟

ASP.NET、C++/CLI、Java 何でもどうぞ

C# と VB.NET の入門サイト


(過去ログ 34 を表示中)
■17260 / )  Re[3]: c# UDPプログラム
□投稿者/ oeppu (3回)-(2008/04/20(Sun) 20:58:46)
 あるサイトで以下のUDPソースがありましたが、自分はソケットを使用したUDPプログラムがあって
UDPの場合ProtocolTypeやSocketTypeをUDP用にソケット生成してbindさせて通信させるのだと思ってました。これでは駄目なんでしょうか?

【当方が思ってたソース例】
int port = 9999;
 Socket sock = new Socket(AddressFamily.InterNetwork,SocketType.Dgram,ProtocolType.Udp);
IPEndPoint ipEndPoint = new IPEndPoint("localhost",port);
sock.Bind(ipEndPoint);

【以下サイトで見つけたソース】
    //文字コードを指定する
System.Text.Encoding enc = System.Text.Encoding.UTF8;

//データを送信するリモートホストとポート番号
string remoteHost = "localhost";
int remotePort = 2002;
//バインドするローカルポート番号
int localPort = 2002;

//ローカルポート番号localPortにバインドする
System.Net.Sockets.UdpClient udp =
new System.Net.Sockets.UdpClient(localPort);

//送信するデータを読み込む
string sendMsg = Console.ReadLine();
byte[] sendBytes = enc.GetBytes(sendMsg);
//リモートホストを指定してデータを送信する
udp.Send(sendBytes, sendBytes.Length,
remoteHost, remotePort);

//データを受信する
System.Net.IPEndPoint remoteEP = null;
byte[] rcvBytes = udp.Receive(ref remoteEP);
string rcvMsg = enc.GetString(rcvBytes);
Console.WriteLine("受信したデータ:{0}", rcvMsg);
Console.WriteLine("送信元アドレス:{0}/ポート番号:{1}",
remoteEP.Address, remoteEP.Port);

//UDP接続を終了
udp.Close();

返信 編集キー/


管理者用

- Child Tree -