2017-01-15 14 views
0

TCP/IP 연결을 사용하는 게임을 만들고 있습니다. 문제는 내가 메시지를 보내고받을 수 있도록 .Invoke를 사용하고 있다는 것입니다.C# 처리기가 .CreateHandler()를 사용할 때 생성 및 실패하지 않음

이 프로그램은 다음과 같이 간다 : 내 첫 번째 창을 해요, 내가 시작하고 같은 서버에 연결 해요 :

{ 
     TcpListener listener = new TcpListener(IPAddress.Any, this.port); 
     listener.Start(); 
     try { 
      this.client = listener.AcceptTcpClient(); 
      gameWindow = new GameWindow(this.client, true); 
      gameWindow.StartGame(); 
     } 
} 

그때 내가 이런 식으로 연결 해요 :

{ 
IPEndPoint ipEnd = new IPEndPoint(this.serverIP, this.port); 
     { 
      try { 
       client.Connect(ipEnd); 
       if (client.Connected) { 
        gameWindow = new GameWindow(this.client, false); 
        gameWindow.StartGame(); 
       } 
      } 
} 

(한 형태이다) gameWindow의 생성자는 다음과 같습니다

public GameWindow(TcpClient thisClient, bool isServer) 
    { 
     InitializeComponent(); 
     this.client = thisClient; 
     this.reader = new StreamReader(thisClient.GetStream()); 
     this.writer = new StreamWriter(thisClient.GetStream()); 

     this.writer.AutoFlush = true; 

    } 

내가 와이한다 서버에 대한 t 클라이언트에 메시지를 보내려면, 다음 클라이언트 (나는 .ShowDialog()를 사용하고 일부 pictureBox의를 생성하는 기능 .startGame()가)

을 시작하지만 아무 내 핸들이 생성되지 얻을 수 있습니다. 나는 GameWindow_Loadthis.createHandle() (여기에 대해 읽음)을 넣으려고했지만 여전히 작동하지 않습니다. 내가있는 메시지를 보내려고하는 경우 : workerSendData.RunWorkerAsync(); 내가 얻을 : 내가 할 수있는 일

Additional information: Invoke or BeginInvoke cannot be called on a control until the window handle has been created.

가 내 handler을 만들어 얻을?

private void workerSendData_DoWork(object sender, DoWorkEventArgs e) 
    { 
     if (client.Connected) { 
      this.writer.WriteLine(this.toSend); // aici trimitem datele. 
      // de modificat : aici vom adauga in lista noastra miscarile. 
      this.Invoke(new MethodInvoker(delegate() { MessageBox.Show("Me:" + this.toSend + "\n"); })); 
     } 
     else { 
      MessageBox.Show("Send failed"); 
     } 
     workerSendData.CancelAsync(); 
    } 

데이터 수신에 대한 나의 코드 :

보내는 메시지 (A 인터넷에서 발견 "솔루션")


내 코드가 작동하지 않는, 내 모든 UI를 잘합니다 Thread.Sleep 사용

private void workerReceiveData_DoWork(object sender, DoWorkEventArgs e) 
    { 
     while (client.Connected) { 
      try { 
       this.received = this.reader.ReadLine(); 
       this.myTurn = true; 
       this.Invoke(new MethodInvoker(delegate() { 
        MessageBox.Show("This has been received: " + this.received); 
        /*this.tbReceive.AppendText("You:" + this.received + "\n");*/ 
       })); 
       this.received = ""; 
      } 
      catch (Exception x) { 
       MessageBox.Show(x.Message.ToString()); 
      } 
     } 
    } 
+0

'Load' 이벤트 내부에서 핸들이 이미 생성되었습니다. 외부에서 클래스를 인스턴스화 한 후에'CreateHandle' 메소드를 사용하십시오. – abto

답변

0

Window이 완전히 초기화되고로드되기 전에 조치를 호출 할 수없는 것으로 보입니다. Windows Forms에서 작업 중이라고 가정하면 @ Greg D에 제공된 솔루션이 this question에 있지만 가장 안전한 방법은 아닙니다.

나는 (예 : Loaded 이벤트를 사용하여) 창을로드 한 후에 만 ​​작업자를 시작하는 방법을 찾으려고 노력합니다. 따라서 핸들이 확실히 준비되었으며이 상황이 발생하지 않습니다.