异步套接字缓冲数组的问题
同步套接字接受数据的时候常常是:
byte[] buffer = new byte[64];
string dataReceived = "";
try
{
while (true)
{
int bytesRead = sender.Receive(buffer);
dataReceived += Encoding.UTF8.GetString(buffer, 0, bytesRead);
if (dataReceived.IndexOf("\r\n") > -1)
break;
}
}
而如果异步套接字这样写,则会报错:
public void ReceiveMsg()
{
byte[] buffer = new byte[64]; //缓冲字节数组
serverSocket.BeginReceive(buffer,0,buffer.Length,SocketFlags.None,new AsyncCallback(receiveCallback),buffer);
}
private void receiveCallback(IAsyncResult ar)
{
try
{
byte[] buffer = (byte[])ar.AsyncState; //缓冲字节数组
StringBuilder sb = new StringBuilder();
while (true)
{
int receivedLength = serverSocket.EndReceive(ar);
sb.Append(Encoding.UTF8.GetString(buffer, 0, receivedLength));
if (sb.ToString().IndexOf("\r\n") > -1)
break;
}
string msgString = sb.ToString();
msgString = msgString.Substring(0,msgString.IndexOf("\r\n"));
Console.WriteLine("收到新消息:{0}",msgString);
}
catch (Exception e)
{
Console.WriteLine(" 接收数据失败:{0}", e.Message);
}
finally
{
ReceiveMsg(); //继续监听消息
}
}
报错:只能为每个异步操作调用一次EndReceive。这样的话要接受的信息如果大于64字节就收不了。
------解决方案--------------------C# code
public void ReceiveMsg()
{
Thread t = new Thread(new ThreadStart(receiveCallback));
t.Start();
}
private void receiveCallback()
{
byte[] buffer = new byte[64];
string dataReceived = "";
try
{
while (true)
{
int bytesRead = sender.Receive(buffer);
dataReceived += Encoding.UTF8.GetString(buffer, 0, bytesRead);
if (dataReceived.IndexOf("\r\n") > -1)
break;
}
}
}
------解决方案--------------------
C# code
StringBuilder sb = new StringBuilder();
byte[] buffer = new byte[64]; //缓冲字节数组
1