Async Tcp Server我只能得到一个客户端。
当我有多个客户端时。我只是在服务器中获得第一个客户端,但其他客户端在客户端连接。
这是我的服务器代码:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net.Sockets;
using System.Threading;
namespace BeginAcceptTcpClientserver
{
class Program
{
static void Main(string[] args)
{
TcpListener listener = new TcpListener(1234);
listener.Start();
listener.BeginAcceptTcpClient(callbake,listenner);
Console.WriteLine("print q to quit");
ConsoleKey key;
do
{
key = Console.ReadKey().Key;
} while (key != ConsoleKey.Q);
}
static void callbake(IAsyncResult ar)
{
TcpClient clienter = ((TcpListener)ar.AsyncState).EndAcceptTcpClient(ar);
Console.WriteLine("---client connect {0}<--{1} ---", clienter.Client.LocalEndPoint, clienter.Client.RemoteEndPoint);
}
}
}
答案 0 :(得分:0)
TcpListener.BeginAcceptTcpClient仅侦听一个传入连接。您需要一次又一次地调用它,可能在您的回调方法中:
static void callbake(IAsyncResult ar)
{
// call BeginAcceptTcpClient here so that it's called everytime a connection is accepted
TcpListener listener = (TcpListener)ar.AsyncState;
listener.BeginAcceptTcpClient(new AsyncCallback(callbake), listener);
TcpClient clienter = listener.EndAcceptTcpClient(ar);
Console.WriteLine("---client connect {0}<--{1} ---", clienter.Client.LocalEndPoint, clienter.Client.RemoteEndPoint);
}