public static void Read_Callback(IAsyncResult ar){ StateObject so = (StateObject) ar.AsyncState; Socket s = so.workSocket; int read = s.EndReceive(ar); if (read > 0) { so.sb.Append(Encoding.ASCII.GetString(so.buffer, 0, read)); s.BeginReceive(so.buffer, 0, StateObject.BUFFER_SIZE, 0, new AsyncCallback(Async_Send_Receive.Read_Callback), so); } else{ if (so.sb.Length > 1) { //All of the data has been read, so displays it to the console string strContent; strContent = so.sb.ToString(); Console.WriteLine(String.Format("Read {0} byte from socket" + "data = {1} ", strContent.Length, strContent)); } s.Close(); } }具体为什么要先endrecive请参照 http://msdn.microsoft.com/zh-cn/library/w7wtt64b.aspx
{
if (this.socket.Connected)
{
//this.SetXinTiao(this.socket);
ReceiveBuffC rbc = this.RBM.getEmpyt();
this.socket.BeginReceive(rbc.buf, 0, this.buff, 0, new System.AsyncCallback(this.ReadCall), rbc);
}
else
{
throw new Exception("not connected.");
}
}
private void ReadCall(System.IAsyncResult ia)
{lock (this)
{
try
{
if (this.closeSocket) return;
int ReceivedNum = this.socket.EndReceive(ia);
ReceiveBuffC rbc = this.RBM.getEmpyt();
ReceiveBuffC rbfc = (ReceiveBuffC)ia.AsyncState;
if (ReceivedNum == 0)
{
throw new System.Net.Sockets.SocketException(10053);
}
if (this.DataReceived != null)
{
byte[] b = new byte[ReceivedNum];
rbfc.getData(ref b, ReceivedNum);
}
rbfc.clear();
if (!this.closeSocket)
{
System.IAsyncResult ar = null;
ar = this.socket.BeginReceive(rbc.buf, 0, this.buff, 0, new System.AsyncCallback(this.ReadCall), rbc);
if (ar.IsCompleted)
{
HJCommon.WriteLog.Instance.AppendErrorLog("ar.AsyncState:"+ar.AsyncState.GetType().FullName+";ar.CompletedSynchronously:"+ar.CompletedSynchronously.ToString());
}
}
}
}
StateObject so = (StateObject) ar.AsyncState;
Socket s = so.workSocket; int read = s.EndReceive(ar); if (read > 0) {
so.sb.Append(Encoding.ASCII.GetString(so.buffer, 0, read));
s.BeginReceive(so.buffer, 0, StateObject.BUFFER_SIZE, 0,
new AsyncCallback(Async_Send_Receive.Read_Callback), so);
}
else{
if (so.sb.Length > 1) {
//All of the data has been read, so displays it to the console
string strContent;
strContent = so.sb.ToString();
Console.WriteLine(String.Format("Read {0} byte from socket" +
"data = {1} ", strContent.Length, strContent));
}
s.Close();
}
}具体为什么要先endrecive请参照
http://msdn.microsoft.com/zh-cn/library/w7wtt64b.aspx