2011-12-04 2 views
0

나는 서로 연결하는 클라이언트와 서버를 만들었습니다. 서버는 클라이언트가 클라이언트에게 보낸 메시지를 처리 ​​할 수 ​​있습니다 (처리 후). 그러나 ... 연결된 두 개의 클라이언트가있는 경우, 처음부터 메시지를 보낸 클라이언트에게만 메시지를 보냅니다. (lol ...)클라이언트 서버 통신 문제 C#

모든 클라이언트에서 모든 클라이언트로 메시지를 보내도록 어떻게 수정합니까?

나는 클라이언트와 서버 사이의 연결을 얻을 수있는 출발점으로 아래의 예를 사용 :

client server communication

난 다음 내 프로그램이 정지됩니다하려고하면

SERVER :

private void HandleClientComm(object client) 
    { 
     TcpClient tcpClient = (TcpClient)client; 
     clientStream = tcpClient.GetStream(); 


      byte[] message = new byte[4096]; 
      int bytesRead; 

      while (true) 
      { 
       bytesRead = 0; 

       try 
       { 
        //blocks until a client sends a message 
        bytesRead = clientStream.Read(message, 0, 4096); 
       } 
       catch (Exception ex) 
       { 
        Debug.Print(ex.Message); 
        break; 
       } 

       if (bytesRead == 0) 
       { 
        //the client has disconnected from the server 
        break; 
       } 
      } 


       //message has successfully been received 
       ASCIIEncoding encoder = new ASCIIEncoding(); 
       foreach (TcpClient c in ListOfClients) 
       { 
       System.Diagnostics.Debug.WriteLine(encoder.GetString(message, 0, bytesRead)); 

       clientStream.Write(message, 0, message.Length); 


      } 

CLIENT :

private void boxChatArea_KeyPress(object sender, KeyPressEventArgs e) 
    { 
     char[] contentForServer = null; 
     boxChatArea.MaxLength = 4000; 


     if (e.KeyChar == (char)Keys.Enter) 
     { 

      client = new TcpClient(); 

      IPEndPoint serverEndPoint = new IPEndPoint(IPAddress.Parse("127.0.0.1"), MainWindow.port); 
      client.Connect(serverEndPoint); 
      clientStream = client.GetStream(); 


      contentForServer = boxChatArea.Text.ToCharArray(); 
      byte[] bytesToSend = System.Text.Encoding.ASCII.GetBytes(contentForServer); 
      clientStream.Write(bytesToSend, 0, bytesToSend.Length); 
      clientStream.Flush(); 
      boxChatArea.Text = null; 

      StartListening(); 

     } 
    } 


    public void StartListening() 
    { 

     HandleServerComm(client); 
    } 




    private void HandleServerComm(object client) 
    { 
     TcpClient tcpClient = (TcpClient)client; 
     clientStream = tcpClient.GetStream(); 

     byte[] message = new byte[4096]; 
     int bytesRead; 

     bytesRead = 0; 

      try 
      { 
       //FREEZES HERE - it doesn't freeze here without the loop that we added within the server... 
       bytesRead = clientStream.Read(message, 0, 4096); 
      } 
      catch (Exception ex) 
      { 
       Debug.Print(ex.Message); 
       //break; 
      } 

      if (bytesRead == 0) 
      { 
       //the client has disconnected from the server 
      } 

      if (bytesRead != 0) 
      { 
       //message has successfully been received 
       ASCIIEncoding encoder = new ASCIIEncoding(); 
       string text = (encoder.GetString(message, 0, message.Length)); 

       if (enterCount >= 1) 
       { 
        displayBoxChatArea.AppendText(Environment.NewLine); 
        displayBoxChatArea.AppendText(text); 
        //displayBoxChatArea.Text = text; 
        Application.DoEvents(); 
       } 
       else 
       { 
        displayBoxChatArea.Text = text; 
        Application.DoEvents(); 
       } 
      } 
     enterCount++; 
     tcpClient.Close(); 

    } 
+0

가능한 중복 (http://stackoverflow.com/questions/7065838/tcp-ip-client-server-not-working-over-internet) – Joe

답변

2

연결된 클라이언트의 목록을 가져와야합니다. 이 같은
시도 뭔가 :

사용자 편집 된 후
List<TcpClient> clients = new List<TcpClient>(); 

private void ListenForClients() 
{ 
    this.tcpListener.Start(); 

    while (true) 
    { 
      //blocks until a client has connected to the server 
      TcpClient client = this.tcpListener.AcceptTcpClient(); 
      if(!clients.Contains(clients)) 
       clients.Add(client); 
    } 
} 

코멘트 :
당신했다 당신의 전송 기능 잘못된 : 먼저, 하나의 클라이언트에서 바로 메시지가 다음 사람에게 보내야합니다.

clientStream = tcpClient.GetStream(); // Not in foreach loop !! 
// ... 
System.Diagnostics.Debug.WriteLine(encoder.GetString(message, 0, bytesRead)); 
foreach(TcpClient client in clients) 
{ 
    // Send message to client 
    st = client.GetStream(); 
    st.Write(message, 0, message.Length); 
} 
[TCP/IP 클라이언트 서버가 인터넷을 통해 작동하지]의
+0

내 코드를 업로드 했으므로 내가하는 일을 살펴볼 수 있습니다. 나는 당신이 제안한 것을 구현했다고 생각합니까? 그러나 어떤 이유로 클라이언트가 메시지를 보내려고 할 때 클라이언트가 얼어 버립니다. – BigBug

+0

@BlueMonster : 'HandleClientComm'에 중단 점을 배치하고 모든 것이 고정되어있는 줄을 이해할 수 있습니까? – Marco

+0

좋아요, 해봤어요. 코드를 업로드하고 코멘트를 달아서 어디서 일어 났는지 볼 수 있습니다 ... – BigBug