我的应用程序中有一个奇怪的错误:“每个套接字只有一个用法”地址。我在tcpview中看到了许多处于CLOSE_WAIT状态的套接字。我设置了延迟超时。但它不起作用。代码如下 服务器:
TcpListener listener = new TcpListener(IPAddress.Any, 7874);
TcpClient client;
listener.Start();
while (true)
{
client = listener.AcceptTcpClient();
ThreadPool.QueueUserWorkItem(ThreadProc, client);
}
private static void ThreadProc(object obj)
{
var client = (TcpClient)obj;
client.Client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.Linger, new LingerOption(true, 0));
var stream = client.GetStream();
using(client){
using (MemoryStream ms = new MemoryStream())
{
int numBytesRead;
byte[] data = new byte[1024];
try
{
while ((numBytesRead = stream.Read(data, 0, data.Length)) > 0)
{
ms.Write(data, 0, numBytesRead);
}
}catch(Exception ex)
{}
var str = Encoding.ASCII.GetString(ms.ToArray(), 0, (int)ms.Length);
}
}
}
客户端:
while (true)
{
try
{
using (TcpClient client = new TcpClient(obj.ToString(), 7874))
{
client.Client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.Linger, new LingerOption(true, 0));
var stream = client.GetStream();
{
stream.Write(bytes, 0, bytes.Length);
}
Thread.Sleep(timeSleep);
//just trying all possible close
client.Client.Shutdown(SocketShutdown.Both);
client.Client.Close(0);
client.Close();
}
}catch(Exception ex)
{
Console.WriteLine(ex);
}
}
但是python客户端正常工作:
while True:
s = socket.socket(
socket.AF_INET, socket.SOCK_STREAM)
try:
s.connect((addr, 7874))
l_onoff = 1
l_linger = 0
s.setsockopt(socket.SOL_SOCKET, socket.SO_LINGER,
struct.pack('ii', l_onoff, l_linger))
s.send(b'test')
while True:
data =s.recv(1024)
break
except Exception as ex:
print(str(datetime.datetime.now())+'NS FAIL')
finally:
s.close()
看起来像.NET tcpclient ignore set linger选项。同样的结果:
client.LingerState = new LingerOption(true, 0);
答案 0 :(得分:0)
我认为你不需要设置LingerOption。我的猜测是你没有在服务器端(被接受的客户端)上释放客户端套接字,然后它在套接字堆栈中保持分配。