服务端开启监听代码示例:
//服务端开启监听示例
Socket ListenSocket;
private void btnStartListen_Click(object sender, EventArgs e)
{
if (ListenSocket == null)
{
ListenSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
IPAddress IPAddress = IPAddress.Parse("192.168.1.195");//获取本机ip
IPEndPoint endpoint = new IPEndPoint(IPAddress, 2333);//网络节点
ListenSocket.Bind(endpoint);
ListenSocket.Listen(10);
Action _a = () =>
{
GetConn(ListenSocket);
};
Task.Factory.StartNew(_a);
}
}
Socket GetedSocketConn;
void GetConn(Socket socket)
{
while (true)
{
Thread.Sleep(10);
GetedSocketConn = socket.Accept();//该函数会一直阻塞线程,直到接收到一个新的连接请求
Console.WriteLine("成功获取连接" + GetedSocketConn.RemoteEndPoint.ToString());
}
}
客户端进行连接代码示例(该示例中,使用了绑定IP及端口的模式,非动态获取端口):
Socket SocketClient;
private void btnStartConnect_Click(object sender, EventArgs e)
{
SocketClient = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
SocketClient.Bind(new IPEndPoint(IPAddress.Parse("0.0.0.0"), 8848));
try
{
IPAddress _otherIPAddress = IPAddress.Parse("192.168.1.195");//获取ip
IPEndPoint _otherEndpoint = new IPEndPoint(_otherIPAddress, 2333);//网络节点
SocketClient.Connect(_otherEndpoint);
}
catch (Exception ex)
{
Console.WriteLine("连接失败:" + ex.ToString());
}
}
关闭连接,使用Socket进行tcp通信时,需要客户端与服务器端都进行关闭,已建立的连接才会彻底关闭,否则客户端所绑定的固定端口就一直是在占用状态,无法再次建立新的连接:
//tcp客户端关闭连接代码
private void btnCloseClient_Click(object sender, EventArgs e)
{
if (SocketClient != null)
{
SocketClient.Close();
}
}
上面的代码执行之后,会发现8848端口处于FIN_WAIT_2状态,需要等待服务器确认关闭连接,才会释放此端口,而再看服务器2333端口为CLOSE_WAIT状态,意为需要调用关闭:
//服务器关闭现有连接
private void btnCloseServerConn_Click(object sender, EventArgs e)
{
if (GetedSocketConn != null)
{
GetedSocketConn.Close();
}
}
等到上面的服务器关闭连接的代码也被执行之后,端口会变为如下状态:
客户端绑定的端口8848会变为TIME_WAIT状态,该状态会持续2MSL(即两倍的分段最大生存期)时间,在此期间该端口仍然是被占用状态,直到时间结束,端口彻底释放: