请问Socket用TcpClient发送完消息后,如何释放本地端口?
是这样的:
我需要做一个程序,要求客户端以固定端口向服务端发送消息。用了TcpClient之后,确实实现了固定IP,只是端口没有及时释放,等到下次连接的时候,他就说端口被占用。我用netstat -a发现该端口的状态是Time_wait,要很久才能自动释放.请问我写的程序有什么问题吗?还是有什么方法可以立即释放端口?
Client:
public static void TcpSend(string mes)
{
IPAddress SeverAddr = IPAddress.Parse(ServerIP);
IPAddress LocalAddr = IPAddress.Parse(ClientIP);
Int32 port = 2113;
int pro = Form1.Pro;
IPEndPoint ipe = new IPEndPoint(LocalAddr, 2125);
TcpClient tcp = new TcpClient(ipe);
Socket sock = tcp.Client;
//Socket sock = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
try
{
sock.Connect(SeverAddr, port);
if (sock.Connected)
{
//Console.WriteLine("Sending Client a simple Message");
byte[] bytes = System.Text.Encoding.UTF8.GetBytes(mes);
sock.Send(bytes);
int nNumBytes;
string Response = null;
do
{
bytes = new byte[1024];
nNumBytes = sock.Receive(bytes);
Response += System.Text.Encoding.UTF8.GetString(bytes);
//Console.WriteLine("Received {0} bytes", nNumBytes);
} while (nNumBytes == 1024);
//Console.WriteLine(Response);
sock.Close();
tcp.Close();
Result re = new Result();
re.Message = Response;
re.ShowDialog();
}
}
catch (Exception e)
{
sock.Close();
tcp.Close();
MessageBox.Show(e.Message);
}
}
Server:
static void Main(string[] args)
{
IPAddress localAddr = IPAddress.Any;
Int32 port = 2113;
Socket sock = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
//connect it to the server in this case it is ur own hostname, the localhost at port 80
IPEndPoint ipEnd = new IPEndPoint(localAddr, port);
sock.Bind(ipEnd);
sock.Listen(25);
while (true)
{
try
{
//TCPMessageSocket ms = new TCPMessageSocket(parse);
Socket Reso = sock.Accept();
MessageHandler me = new MessageHandler(Reso);
Thread th = new Thread(new ThreadStart(me.HandleMessage));
th.Start();
}
catch (Exception e)
{
Console.WriteLine("Thread error {0}", e.Message);
}
}
}