gpt4 book ai didi

c# - 如何正确停止异步 TcpListener?

转载 作者:太空宇宙 更新时间:2023-11-03 14:38:53 27 4
gpt4 key购买 nike

我的窗口上有两个 Button 连接到两个 ICommands:

public ICommand Start { get; set; }
public ICommand Stop { get; set; }

Constructor 中初始化如下:

Start = new Command(StartServer, (o) => !IsListening);
Stop = new Command(StopServer, (o) => IsListening);

然后做这些:

async void StartServer(object obj)
{
server.Start();
IsListening = true;
Status = "Listening";
try
{
while (IsListening)
{
var cw = new ClientWrapper();
cw.Client = await server.AcceptTcpClientAsync();
cw.EndPoint = cw.Client.Client.RemoteEndPoint;
Pool.Add(cw);
HandleClient(cw);
}
}
catch (Exception e)
{
throw;
}
}


void StopServer(object obj)
{
DisposeClients();
server.Stop();
IsListening = false;
Status = "Start Server";
}

当我单击 Start 时,它开始监听并毫无问题地接受客户端。在没有任何客户端的情况下,如果我只是Start 服务器然后单击Stop,它会正常执行StopServer 函数然后点击ICommandExecute函数,来到StartServer方法的catch block ! e 中的消息是:

Cannot access a disposed object. Object name: 'System.Net.Sockets.Socket'.

我不希望它转到catch block !如何正确处理?

最佳答案

using System;
using System.Net;
using System.Net.Sockets;
using System.Threading;

namespace tcplistenertest
{
class Program
{
static void Main(string[] args)
{
Thread listenerThread = StartBackgroundThread(new ThreadStart(ThreadProc));

while(Console.ReadLine() != string.Empty)
{
}

mListener.Stop();
listenerThread.Join();
}

static void ThreadProc()
{
try
{
mListener = StartListening();

AcceptLoop(mListener);
}
catch(Exception e)
{
Console.WriteLine($"ThreadProc error: {e.Message}");
Console.WriteLine($"Stack trace:{Environment.NewLine}{e.StackTrace}");
}
}

static Thread StartBackgroundThread(ThreadStart task)
{
Thread thread = new Thread(task);
thread.IsBackground = true;
thread.Start();
return thread;
}

static TcpListener StartListening()
{
TcpListener result = new TcpListener(IPAddress.Any, PORT);
result.Start();

return result;
}

static void AcceptLoop(TcpListener listener)
{
// this is the main loop of the Socket based server
while (true)
{
Socket socket = null;
try
{
Console.WriteLine("Accepting connection...");
socket = AcceptConnection(listener);
Console.WriteLine($"Connection accepted from {socket.RemoteEndPoint}");
}
catch (SocketException e)
{
Console.WriteLine($"Socket error accepting connection: {e.Message}");
Console.WriteLine($"Stack trace:{Environment.NewLine}{e.StackTrace}");
break;
}
catch (Exception e)
{
Console.WriteLine($"Generic error accepting connection: {e.Message}");
Console.WriteLine($"Stack trace:{Environment.NewLine}{e.StackTrace}");
break;
}

try
{
socket.Close();
}
catch (Exception e)
{
Console.WriteLine($"Error closing socket: {e.Message}");
Console.WriteLine($"Stack trace:{Environment.NewLine}{e.StackTrace}");
break;
}
}

Console.WriteLine("Accept loop thread stopping");
}

static Socket AcceptConnection(TcpListener listener)
{
Socket socket = listener.AcceptSocket();
try
{
socket.SetSocketOption(SocketOptionLevel.Tcp, SocketOptionName.Debug, 1);
LingerOption optionValue = new LingerOption(true, 3);

socket.SetSocketOption(SocketOptionLevel.Socket,
SocketOptionName.Linger, optionValue);

return socket;
}
catch (Exception)
{
socket.Close();
throw;
}
}

static TcpListener mListener;
const int PORT = 55000;
}
}

关于c# - 如何正确停止异步 TcpListener?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58517207/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com