看个简单的例子,也许有帮助:
public static ManualResetEvent done = new ManualResetEvent(false);
static int count = 1;
public static void Main(String[] Args)
{
Socket socket = new Socket(AddressFamily.InterNetwork,SocketType.Stream,ProtocolType.Tcp);
byte[] buf = new byte[500];
try
{
IPEndPoint remote = new IPEndPoint(Dns.Resolve(Dns.GetHostName()).AddressList[0],80);
socket.Connect(remote);
byte[] send = Encoding.ASCII.GetBytes("GET /test/aspx/asp1.aspx HTTP/1.1\r\nHost:  server " +
"\r\nConnection: Close\r\n\r\n");
socket.Send(send,send.Length,0);
while (true) {
socket.BeginReceive(buf,0,buf.Length,SocketFlags.Partial,new AsyncCallback(callback),socket);
done.WaitOne();
Thread.Sleep(1000);
if (count == 0) {
break;
}
Console.WriteLine(Encoding.ASCII.GetString(buf, 0, count));
}
socket.Close();
}
catch(Exception e)
{
Console.WriteLine("Has Exception!");
}
}
static void callback(IAsyncResult ar)
{
byte[] buf = new byte[500];
Socket socket = (Socket) ar.AsyncState;
count = socket.EndReceive(ar);
done.Set();
}