yangli-1128

c# socket 断网

在c#中断网的情况下 Receive 是收不到消息的。


处理方式先设置接收超时


  _socket.ReceiveTimeout = 1000 * 30;


再设置IOControl


byte[] inValue = new byte[] { 1, 0, 0, 0, 0x20, 0x4e, 0, 0, 0xd0, 0x07, 0, 0 };


_socket.IOControl(IOControlCode.KeepAliveValues, inValue, null);


------------------------------------------------


socket.IOControl(IOControlCode.KeepAliveValues, inOptionValues,  null );


inOptionValues的定义,在C++里它是一个结构体


struct  tcp_keepalive

 { 

    u_long  onoff; //是否启用Keep-Alive

    u_long  keepalivetime; //多长时间后开始第一次探测(单位:毫秒)

    u_long  keepaliveinterval; //探测时间间隔(单位:毫秒)

} ; 


uint  dummy  =   0 ;

byte [] inOptionValues  =   new   byte [Marshal.SizeOf(dummy)  *   3 ];

BitConverter.GetBytes(( uint ) 1 ).CopyTo(inOptionValues,  0 );//是否启用Keep-Alive

BitConverter.GetBytes(( uint ) 5000 ).CopyTo(inOptionValues, Marshal.SizeOf(dummy));//多长时间开始第一次探测

BitConverter.GetBytes(( uint ) 5000 ).CopyTo(inOptionValues, Marshal.SizeOf(dummy)  *   2 );//探测时间间隔


--------------


https://blog.css8.cn/post/13770997.html


标签: socket c
上一篇 下一篇
评论
©yangli-1128 | Powered by LOFTER