Socket通信中断检测问题
WaitData()方法服务器端是一个线程方法,每一个连接上来的用户都会开一个线程来跟它通信,问题是当有一用户由于网络中断了,服务器端提供的该线程就死在那里等待接收,根本没有检测到用户端已经断开了。哪位高手能提出一个解决方案。
Public Sub StartReceive()
.........
While True
Array.Clear(bytes, 0, 20)
Try
ss.Receive(bytes)
Catch ex As Exception
End Try
.......
End While
End Sub
--------------------编程问答--------------------
--------------------编程问答-------------------- 命名空间:
struct tcp_keepalive
{
public uint onoff;
public uint keepalivetime;
public uint keepaliveinterval;
};
tcp_keepalive keepalive;
keepalive.onoff = 1;
keepalive.keepalivetime = 5000;
keepalive.keepaliveinterval = 5000;
byte[] optionValue = StructOp.StructToBytes(keepalive);
//接受客户端连接
Socket client = this.socket.Accept();
//设置Keep-Alive探测时间
client.IOControl(IOControlCode.KeepAliveValues, this.optionValue, null);
//这种方法我是参考牧野的Blog改的.
//有关结构体与byte数组的转换,详见我的Blog.
/// <summary>
/// 结构体转byte数组
/// </summary>
/// <param name="structObj">要转换的结构体</param>
/// <returns>转换后的byte数组</returns>
public static byte[] StructToBytes(object structObj)
{
//得到结构体的大小
int size = Marshal.SizeOf(structObj);
//创建byte数组
byte[] bytes = new byte[size];
//分配结构体大小的内存空间
IntPtr structPtr = Marshal.AllocHGlobal(size);
//将结构体拷到分配好的内存空间
Marshal.StructureToPtr(structObj, structPtr, false);
//从内存空间拷到byte数组
Marshal.Copy(structPtr, bytes, 0, size);
//释放内存空间
Marshal.FreeHGlobal(structPtr);
//返回byte数组
return bytes;
}
using System.Net.Sockets;
using System.Runtime.InteropServices;
--------------------编程问答-------------------- 楼主的代码没头没尾的没法看,问题也没交待清楚
长连接还是短连接?
ss是什么类型? --------------------编程问答-------------------- 晕,用.Net2003的,.Net FrameWork 1.1的,居然没有IOControlCode接口,真的绝境了啊。
狂晕中...... --------------------编程问答-------------------- 没有IOControlCode可以自己写:
Public Enum IOControlCode As Long
' Fields
AbsorbRouterAlert = &H98000005
AddMulticastGroupOnInterface = &H9800000A
AddressListChange = &H28000017
AddressListQuery = &H48000016
AddressListSort = &HC8000019
AssociateHandle = &H88000001
AsyncIO = &H8004667D
BindToInterface = &H98000008
DataToRead = &H4004667F
DeleteMulticastGroupFromInterface = &H9800000B
EnableCircularQueuing = &H28000002
Flush = &H28000004
GetBroadcastAddress = &H48000005
GetExtensionFunctionPointer = &HC8000006
GetGroupQos = &HC8000008
GetQos = &HC8000007
KeepAliveValues = &H98000004
LimitBroadcasts = &H98000007
MulticastInterface = &H98000009
MulticastScope = &H8800000A
MultipointLoopback = &H88000009
NamespaceChange = &H88000019
NonBlockingIO = &H8004667E
OobDataRead = &H40047307
QueryTargetPnpHandle = &H48000018
ReceiveAll = &H98000001
ReceiveAllIgmpMulticast = &H98000003
ReceiveAllMulticast = &H98000002
RoutingInterfaceChange = &H88000015
RoutingInterfaceQuery = &HC8000014
SetGroupQos = &H8800000C
SetQos = &H8800000B
TranslateHandle = &HC800000D
UnicastInterface = &H98000006
End Enum
--------------------编程问答-------------------- 先收藏
补充:.NET技术 , VB.NET