a udp echo client
和我的UdpEchoServer配合使用,在本机上试验用。设定接收的时间限制是3秒。
/*
* Created by SharpDevelop.
* User: xuhx
* Date: 2004-6-19
* Time: 14:21
*
* To change this template use Tools | Options | Coding | Edit Standard Headers.
*/
using System;
using System.Net;
using System.Net.Sockets;
using System.Text;
namespace DefaultNamespace
{
/// <summary>
/// Description of Class1.
/// </summary>
public class UdpEchoClient
{
private static readonly int BUF_SIZE=2048;
public static void Main(){
Socket clientSocket=new Socket(AddressFamily.InterNetwork,
SocketType.Dgram,
ProtocolType.Udp
);
clientSocket.SetSocketOption(SocketOptionLevel.Socket,
SocketOptionName.ReceiveTimeout,
3000
);
EndPoint serverEndPoint=new IPEndPoint(IPAddress.Parse("127.0.0.1"),
8004
);
Console.WriteLine("echo client start");
while(true){
string input=Console.ReadLine();
if("exit"==input.ToLower()){
clientSocket.Close();
Console.WriteLine("echo client stop.");
break;
}
byte[] buf=Encoding.ASCII.GetBytes(input);
clientSocket.SendTo(buf,SocketFlags.None,serverEndPoint);
buf=new byte[BUF_SIZE];
EndPoint remoteEndPoint=new IPEndPoint(IPAddress.Any,0);
try{
int receive=clientSocket.ReceiveFrom(buf,ref remoteEndPoint);
string strReceive=Encoding.ASCII.GetString(buf,0,receive);
Console.WriteLine("echoed from server: {0} message:{1}",remoteEndPoint,strReceive);
}catch(SocketException e){
Console.WriteLine(e.Message);
}
}//while
}
}
}