herein , i just wanner illuminate two problems.
first ,i want to show how to use the beginReceive and then if i have a big buffer to receive a short string,why i get the string exceptional.
now , follow me to see it
code:
we write a class as transferring data object
class state
{
public Socket _mySocket{set;get;}
byte[] _buff{set;get;}
}
we invoke the function beginreceive like this
_myListenSocket.beginreceive(buff,0,buff.length,sockettype.none,endreceivecallback,stateobject);
in the endreceivecallback ,we code like this
state mystate = ar.AsyncState as state;
socket mySocket = myState.sokcet;
byte[] mybuff = myState.buff;
int ret =mySocket.EndReceive(ar);
then problem 2 has coming ,check my code carefully
mystring = Encoding.utf8.getstring(buff,0,buff.length);
so we have got the string :这个是测试程序/0/0....
when we run the test program ,just got exceptional string that we don't want;
now ,we analyse this situation
first ,we definitely didn't clear the buff ,if we get the msg "这个是测试程序" at the previous time and now we had received msg "压力测试",we get "压力测试试程序" at last!
but now you perhaps ask me when we change the length from the size of buff to receiving the real length ,we don't clear the buffer also,why the reslut is ok; do a pretty work!
actually,it did the same thing the two invoke methods;just the method 2 ,we display the length we assigned;
so we definitely did not clear the buffer
at last we should invoke the beginreceive in endreceivecallback;
now there is a problem about close the socket using to receive msg
if we want to close the socket ,we must do it like this
code:
void CloseSocket()
{
if(AcceptSocket != null&& AcceptSocket.Connected)
{
AcceptSocket.Shutdown(SocketShutdown.Both);
AcceptSocket.Close();
AcceptSocket = null;
}
}
when we need use the socket ,we judge it whether equal null
if(AcceptSocket == null)
return;
int ret = tempAcceptSocket.EndReceive(ar);
...