百度了一圈都没结果,不是扯心跳包就是乱说,无意中发现的方法了
。
先上我的代码:
public class TCPIPServer
{
#region 成员
private static TCPIPServer tcpIPServer;
private static Socket socket;
#endregion
#region 属性
#endregion
#region 方法
/// <summary>
/// 创建服务器
/// </summary>
/// <param name="port"></param>
/// <returns></returns>
public static TCPIPServer CreateServer(int port)
{
if (tcpIPServer == null && socket == null)
{
return tcpIPServer = new TCPIPServer(port);
}
return tcpIPServer;
}
private TCPIPServer(int port)
{
socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
IPEndPoint ipEndPoint = new IPEndPoint(IPAddress.Any, port);
socket.Bind(ipEndPoint);
socket.Listen(10);
BeginAccept(socket);
}
/// <summary>
/// TCPIP消息事件
/// </summary>
public event EventHandler<ClientInfoEvent> TcpMsgEvent;
/// <summary>
/// TCPIP登陆事件(不支持获取TCPIP数据)
/// </summary>
public event EventHandler<ClientInfoEvent> TcpClientInfoEvent;
private Dictionary<string, Socket> ConnectionList = new Dictionary<string, Socket>();
private void BeginAccept(Socket objsocket)
{
objsocket.BeginAccept(callback=> {
var client= objsocket.EndAccept(callback);
var ip = client.RemoteEndPoint.ToString();
if (!ConnectionList.ContainsKey(ip))
{
ConnectionList.Add(ip,client);
TcpClientInfoEvent?.Invoke(tcpIPServer,new ClientInfoEvent(ConnectionList));
}
BeginReceive(client,0);
BeginAccept(objsocket);
},null);
}
private void BeginReceive(Socket objsocket,int num)
{
byte[] buffer = new byte[4096];
objsocket.BeginReceive(buffer,0,buffer.Length,SocketFlags.None,callback=>
{
var length= objsocket.EndReceive(callback);
if (length>0)
{
var bytes = new byte[length];
Array.Copy(buffer,bytes,length);
TcpMsgEvent?.Invoke(tcpIPServer,new ClientInfoEvent(new UdpReceiveResult(bytes,objsocket.RemoteEndPoint as IPEndPoint), ConnectionList));
num = 0;
BeginReceive(objsocket, num);
}
else if(length==0)//就是我length=0就是断开了
{
ConnectionList.Remove(objsocket.RemoteEndPoint.ToString());
objsocket.Dispose();
}
},null);
}
public void Send(byte[] buffer, EndPoint endpoint)
{
ConnectionList[endpoint.ToString()].BeginSend(buffer,0,buffer.Length,SocketFlags.None,callback=>
{
ConnectionList[endpoint.ToString()].EndSend(callback);
},null);
}
#endregion
}
当接收到的数据长度=0的时候此时客户端就请求断开连接了。
就这么简单