2016-09-22 2 views
0

내 소켓 서버는 지금까지 매우 간단하다 :TCP C# 소켓 서버에서 여러 활성 연결을 처리하는 방법은 무엇입니까?

 public static void listen() 
    { 
     TcpListener server = null; 
     IPAddress address = IPAddress.Parse("127.0.0.1"); 
     try 
     { 
      server = TcpListener.Create(5683); 
      server.Start(); 

     } 
     catch (Exception e) 
     { 
      Console.WriteLine(e.StackTrace); 
     } 


     while (true) 
     { 
      Thread.Sleep(10); 
      TcpClient client = server.AcceptTcpClient(); 
      Console.WriteLine("Accepted Client"); 

      Thread thread = new Thread (new ParameterizedThreadStart(SwordsServer.ClientHandler)); 
      thread.IsBackground = true; 
      thread.Start(client); 
     } 
    } 

    public static void ClientHandler(object c) 
    { 
     TcpClient client = (TcpClient)c; 
     NetworkStream netstream = client.GetStream(); 
     bool connected = true; 
     while (connected) 
     { 
      Thread.Sleep(10); 
      try 
      { 
       byte[] bytes = new byte[client.ReceiveBufferSize];     
       netstream.Read(bytes, 0, bytes.Length); 
       Console.WriteLine("got data"); 
       netstream.Write(bytes, 0, bytes.Length); 

      } 
      catch (Exception e) 
      { 
       connected = false; 
       Console.WriteLine(e); 
       Console.WriteLine(e.StackTrace); 
      } 
     } 
    } 

내 질문은, 개념적인 수준에서, 당신은 어떻게 각각의 고유 한 client을 감시 할 특정 클라이언트에 다른 스레드에서 업데이트를 보낼 수 있습니까?

예를 들어 특정 클라이언트에 대한 데이터가있는 경우이를 브로드 캐스팅하지 않고 어떻게 클라이언트에 전달합니까? 또는 클라이언트가 더 이상 연결되어 있지 않으면 어떻게 알 수 있습니까?

미리 도움을 청하십시오!

+1

목록 개체 목록을 추가하십시오. 클라이언트. – jdweng

+0

하지만 그 목록에있는 특정 TCP 클라이언트를 어떻게 참조 할 수 있습니까? 나는 어떻게 그들을 구분할 것인가? – MrDysprosium

+0

한 가지 방법은 클라이언트의 IP 주소를 사용하는 것입니다. 또는 각 클라이언트에게 ID를 제공하십시오. – jdweng

답변

1

여러 연결을 수락하기위한 구현은 익명 클라이언트를 만듭니다. 즉, 두 개 이상의 연결 후에 올바른 클라이언트를 식별 할 수 없습니다. 식별이 문제라면, 클라이언트가 "Client1"과 같은 식별자를 서버에 보내도록 한 가지를 할 수 있습니다. 사전을 만들고 ClientHandler() 메서드에서 클라이언트에서 식별자를 읽고 TCPClient의 객체를 사전에 추가합니다.

Dictionary<string, TCPClient> dictionary = new Dictionary<string, TCPClient>(); 


public static void ClientHandler(object c) 
    { 
     TcpClient client = (TcpClient)c; 
     NetworkStream netstream = client.GetStream(); 
     bool connected = true; 
     while (connected) 
     { 
      Thread.Sleep(10); 
      try 
      { 
       byte[] bytes = new byte[client.ReceiveBufferSize]; 

       //read the identifier from client 
       netstream.Read(bytes, 0, bytes.Length); 

       String id = System.Text.Encoding.UTF8.GetString(bytes); 

       //add the entry in the dictionary 
       dictionary.Add(id, client); 
       Console.WriteLine("got data"); 
       netstream.Write(bytes, 0, bytes.Length); 

      } 
      catch (Exception e) 
      { 
       connected = false; 
       Console.WriteLine(e); 
       Console.WriteLine(e.StackTrace); 
      } 
     } 
    } 

하는 메모를 수행합니다 : 응용 프로그램이 동적으로 업데이트가 전송되어야하는 클라이언트에 결정하기에 충분 지적해야한다

그래서 수정 된 코드는 다음과 같이 될 것이다.

+0

네, 그건 내 UDP 프로그램에서 무엇을하는지, 단순히 그들의 Client Object 값에 대한 키로 IP/소켓 튜플을 사용합니다. 감사! – MrDysprosium

+0

안녕하세요 Rishabh 쿠마! 최근에 비슷한 문제가 생겼습니다. 나는 당신과 같은 한 가지 해결책으로 생각했지만 서버가 오랫동안 돌아가고 많은 클라이언트를 가지고있을 때 내 문제가 나타납니다. 문제는 응용 프로그램이 많은 스레드를 생성하기 시작하고 시간이 지나면 다시 복원 할 때까지 더 많은 연결을 허용하지 않는다는 것입니다. 그럼, 그걸로 손을 내줄 수 있니? 감사! –

+0

@RishabhKumar 글쎄,이 코드는 내가 한동안 기억에 문제가 있다고 말했을 때 말이다. 도와 줘서 고마워! https://pastebin.com/sx6iVnZD –

관련 문제