【发布时间】:2018-09-25 04:15:03
【问题描述】:
我需要使用 TcpListener 监听多个端口,并且我需要 TcpListener 接受多个连接并单独处理每个端口,这是我编写的代码,但正如您所看到的,它只监听第一个端口,然后转到 while(true) 和侦听到达该端口的所有连接。知道我如何才能监听多个端口的多个连接吗?
private static async Task TcpServerAsync()
{
try
{
IPAddress ip;
if (!IPAddress.TryParse(ConfigurationManager.AppSettings["ipAddress"], out ip))
{
Console.WriteLine("Failed to get IP address, service will listen for client activity on all network interfaces.");
ip = IPAddress.Any;
}
foreach (Ports port in Ports.GetValues(typeof(Ports)))
{
Log.Info("Starting listener...");
var tcpListener = new TcpListener(ip, (int)port);
tcpListener.Start();
Log.Info("Listening...");
var startTimeSpan = TimeSpan.Zero;
var periodTimeSpan = TimeSpan.FromSeconds(10000000);
while (true)
{
TcpClient client = await tcpListener.AcceptTcpClientAsync();
client.Client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.KeepAlive, 1);
HandleByPortNumber(client, (int)port);
}
}
}
catch (Exception ex)
{
Log.Info("Error Happened : " + ex + ex.InnerException);
}
}
和
public static void HandleByPortNumber(TcpClient client , int portNumber)
{
switch (portNumber)
{
case (int)Ports.Teltonica:
var cw = new Teltonika.TcpClientService(client);
ThreadPool.UnsafeQueueUserWorkItem(x => ( (Teltonika.TcpClientService)x).Run(), cw);
break;
case (int)Ports.OBDTracker:
break;
}
}
和
public enum Ports
{
Teltonica = 3000,
OBDTracker = 3001
}
【问题讨论】:
-
查看 msdn 示例:docs.microsoft.com/en-us/dotnet/framework/network-programming/…。侦听器可以在同一端口上侦听默认的 100 个连接。您可以打开多个侦听器并对多个侦听器使用相同的异步接受/接收方法。示例是传输层代码,没有很好的应用层。应用层只是响应收到的消息。一年多前,我帮助某人处理了一个处理多个连接的复杂应用程序层。请参阅下一条评论。
标签: c# .net sockets tcplistener