2013-03-24 2 views
-2

서버와 클라이언트를 다루는 응용 프로그램을 작성하고 있습니다. 필자는 서버가 여러 클라이언트를 처리하는 방법을 알 필요가 없습니다. 여기에서 제가 문제가 있습니다. 현재 서버 측은 하나의 클라이언트 만 처리합니다. 그래서 어떻게 여러 클라이언트를 처리 할 수 ​​있습니다.여러 클라이언트 처리

답변

2

TcpListener를 열린 상태로 유지하고 여러 연결을 허용 할 수 있습니다. 여러 연결을 효율적으로 처리하려면 서버 코드를 멀티 스레드해야합니다.

static void Main(string[] args) 
{ 
    while (true) 
    { 

     Int32 port = 14000; 
     IPAddress local = IPAddress.Parse("127.0.0.1"); 

     TcpListener serverSide = new TcpListener(local, port); 
     serverSide.Start(); 
     Console.Write("Waiting for a connection with client... "); 
     TcpClient clientSide = serverSide.AcceptTcpClient(); 
     Task.Factory.StartNew(HandleClient, clientSide); 
    } 
} 

static void HandleClient(object state) 
{ 
    TcpClient clientSide = state as TcpClient; 
    if (clientSide == null) 
     return; 

    Console.WriteLine("Connected with Client"); 
    clientSide.Close(); 
} 

지금 당신은 당신이 메인 루프가 추가 연결을 수신 계속하면서 HandleClient 수행해야 처리의 모든 작업을 수행 할 수 있습니다.

관련 문제