Socket 异步接受

  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);

...

 

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值