2017-02-10 1 views
0

목표는 두 클라이언트 (두 클라이언트 모두에서 실행되고 텍스트 메시지와 동기화되는 GUI 프로그램)에 대해 동기화 된 작업 영역을 만드는 것입니다. 현재 두 개의 단추가 있습니다. 첫 번째 단추는 서버와 소켓을 만들고 두 번째 단추는 새 양식 (현재 빈 양식 인 Form2)을 엽니 다. 버튼 2를 클릭하면 현재 클라이언트의 양식이 열리고 다른 클라이언트가 양식을 여는 메시지가 전송됩니다. 어떤 이유로 인해 버튼을 클릭하여 표시되는 첫 번째 양식은 성공하지만 첫 번째 클라이언트의 메시지로 표시하려고하는 다른 클라이언트는 성공하지 못하고 "응답하지 않음"입니다. 두 번째 클라이언트의 양식이 응답하지 않는 이유는 무엇입니까? 두 클라이언트 모두에서 Form2의 인스턴스가 먼저 정의됩니다. 두 클라이언트의 코드가 동일한 코드입니다. 항상 시도 스레드를 -서버에서 메시지를 수신하여 양식을 열려고 시도했습니다.

private void button2_Click(object sender, EventArgs e) 
    {msgtosend.Add(Encoding.ASCII.GetBytes("/OpenNP")); 
      Np.Show();/* Np is defined as a global variable and built in Form1_load*/} 

3 CrazyReceivingThread : 코드 샘플 :

private void button1_Click(object sender, EventArgs e) 
    { 
     try 
     { 
      IPAddress ipAddress = new IPAddress(new byte[] { 127, 0, 0, 1 }); 
      IPEndPoint remoteEP = new IPEndPoint(ipAddress, 11000); 
      Socket Server_Socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); 
      try 
      { 
       Server_Socket.Connect(remoteEP); 
       Thread SendingThread = new Thread(new ParameterizedThreadStart(CrazySendingThread)); 
       Thread RecievingThread = new Thread(new ParameterizedThreadStart(CrazyReceivingThread)); 

       SendingThread.Start(Server_Socket); /*A thread that always sends the messages in 'msgtosend' list.*/ 
       RecievingThread.Start(Server_Socket);/* A thread that always try to receive a message from the server(if there isn't it waits).*/ 
      } 
      catch (ArgumentNullException ane) 
      { 
       Console.WriteLine("ArgumentNullException : {0}", ane.ToString()); 
      } 
      catch (SocketException se) 
      { 
       Console.WriteLine("SocketException : {0}", se.ToString()); 
      } 
      catch (Exception ex) 
      { 
       Console.WriteLine("Unexpected exception : {0}", ex.ToString()); 
      } 
     } 
     catch (Exception ex) 
     { 
      Console.WriteLine(ex.ToString()); 
     } 
    } 

2 버튼 2를 클릭하여 새 폼을 엽니 다 : 1 버튼 1을 클릭하여 서버에 연결 받을 :

public void CrazyReceivingThread(object srv) 
    { 
     string msg = ""; 

     Socket srvr = (Socket)srv; 
     byte[] data = new byte[1024]; 
     while (true) 
     { 
      System.Threading.Thread.Sleep(20); 
      int bytesRec = srvr.Receive(data); 
      msg = Encoding.ASCII.GetString(data, 0, bytesRec); 
      string[] msg_array = msg.Split(' '); 
      try { 
       switch (msg_array[0]) 
       { 
        case "/Mouse_pos": 
         {/*is not relevant for the question...*/}break; 

        case "/OpenNP": 
         { 
           try 
           { 
            Np.Show(); 
           } 
           catch /*The form is 'Not responding' but this exception is **not** being caught.*/ 
           { 
            Console.WriteLine("Form is not shown."); 
           }  
         } 
         break; 
       } 
      } catch(ArgumentNullException e) { 
       Console.WriteLine(e.Message); 
      } 
     } 
    } 
+1

사용중인 코드의 예를 들려 줄 수 있습니까? 메시지가 제대로 전달되고 있습니까? 소켓이 열렸습니까? 두 번째 클라이언트가 연결되어 있습니까? – pstrjds

+0

코드 샘플이 추가되었습니다. @pstrjds 두 클라이언트가 모두 연결되어 있는데 두 번째 클라이언트에서 양식을 보았지만 응답이 없으므로 메시지가 제대로 전달되지 않습니다. 서버에 메시지가 표시되어 연결에 문제가 없습니다. –

답변

0

양식이 응답하지 않는 이유 당신이 백그라운드 스레드에서 Form를 시작하려고하는 것입니다 . UI 스레드 (메시지 펌프가있는 스레드)에서 양식을 열어야합니다. 이것은 Invoke (또는 BeginInvoke)을 호출하여 수행됩니다. 기본 폼 코드를 나열하지 않으므로 정확한 코드 대체를 말할 수는 없지만 기본 폼에 대한 참조를 스레드 메서드에 전달하고 해당 메서드에서 Form.Show을 호출하려는 경우 전화 :

case "/OpenNP": 
{ 
    try 
    { 
     // where mainForm is a reference to the form 
     // that contains the buttons, the main form that is shown 
     mainForm.Invoke((Action)(() => Np.Show())); 
    } 
    catch (Exception ex) 
    { 
     Console.WriteLine("Form is not shown. " + ex.ToString()); 
    }  
} 
break; 
+0

https://gyazo.com/e5ab4cd18e840987755cd3f56bd06160 이 줄을 작성한 후에 구문 오류가 3 개 있습니다. 'mainForm'을 내 프로젝트에 표시된 양식 인 'Form1'로 변경했습니다. –

+0

@OfirAizenberg - 업데이트했습니다. 나는 괄호 세트를 놓쳤다. 내 잘못이야. – pstrjds

관련 문제