请问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);
}
}
}
相关推荐
C# Socket实现TCPClient
C#用Socket实现TCPClient,简单好用的测试代码
C#高级篇(三)---Socket 、TcpClient 、UdpClient
TCP---Socket通讯 服务端 using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Sockets; using System.Text; using System.Threading.Tasks; namespace _021_soc
C# Socket网络通信_TCP(TcpListener和TcpClient)
简单Socket-Tcp通信 1.关键字-TcpListener 需要引用命名空间: using System.Net; using System.Net.Sockets; 服务端代码: using System; using System.Net; using System.Net.Sockets; using System.Text; namespace Socket_TcpListen...
C# 基于socket实现的异步TcpServer和TcpClient
C#编写的TCP异步通信,采用Socket实现,(还可用C#对Socket的封装TcpClient和TcpListener实现) 包含服务端及客户端完整代码
C# 使用 TcpClient,Socket 聊天
1. 使用C#的TcpClient写的聊天软件 2. 代码特点: 书写规范, 【最简单】的TcpClient用法, 3. 这样的好处是看了一目了然,而不是给你一个乱七八糟的项目让你去看了一上午还没看明白TcpClient, Socket到底怎么使用的


