2015-02-03 3 views
-1

Visual Basic에서 간단한 TCP/IP 채팅 응용 프로그램에 문제가 있습니다. 서버 응용 프로그램을 실행할 때 창은 표시되지 않고 이유를 모르겠습니다. 그러나 서버가 제대로 작동하고 있습니다. 서버 코드는 아래와 같습니다.응용 프로그램을 실행할 때 창이 표시되지 않습니다.

Imports System.Net.Sockets 
Imports System.Net 

Public Class Form1 
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load 
    Try 

     Dim server As TcpListener 
     server = Nothing 

     ' Set the TcpListener on port 13000. 
     Dim port As Int32 = 13000 
     Dim localAddr As IPAddress = IPAddress.Parse("127.0.0.1") 

     server = New TcpListener(localAddr, port) 

     ' Start listening for client requests. 
     server.Start() 

     ' Buffer for reading data 
     Dim bytes(1024) As Byte 
     Dim data As String = Nothing 

     ' Enter the listening loop. 
     While True 
      TextBox1.Text = "Waiting For connections" 

      ' Perform a blocking call to accept requests. 
      ' You could also user server.AcceptSocket() here. 
      Dim client As TcpClient = server.AcceptTcpClient() 

      TextBox2.Text = "Connected!" 

      data = Nothing 

      ' Get a stream object for reading and writing 
      Dim stream As NetworkStream = client.GetStream() 

      Dim i As Int32 

      ' Loop to receive all the data sent by the client. 
      i = stream.Read(bytes, 0, bytes.Length) 

      While (i > 0) 
       ' Translate data bytes to a ASCII string. 
       data = System.Text.Encoding.ASCII.GetString(bytes, 0, i) 
       TextBox3.Text = "Received:" & data 

       ' Process the data sent by the client. 
       data = data.ToUpper() 
       Dim msg As Byte() = System.Text.Encoding.ASCII.GetBytes(data) 

       ' Send back a response. 
       stream.Write(msg, 0, msg.Length) 
       TextBox4.Text = "Sent:" & data 

       i = stream.Read(bytes, 0, bytes.Length) 

      End While 

      ' Shutdown and end connection 
      client.Close() 
     End While 

     server.Stop() 
    Catch ex As Exception 

    End Try 
End Sub 
End Class 

답변

0

Form.Load의 UI 스레드에서 서버를 실행하고 있습니다. Form.Load이 완료 될 때까지 양식이 표시되지 않습니다. 서버 로직을 새 스레드에서 실행해야합니다. 따라서 UI가 아닌 스레드에서 UI (예 : TextBox1.Text = "Waiting For connections")를 업데이트 할 수 없으므로 Invoke을 사용해야합니다. 예 : (완전히 테스트되지 않았으므로 시도해 볼 내용을 알려주십시오) :

Imports System.Threading 

Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load 
    Dim t = New Thread(AddressOf RunServer) 
    t.Start() 
End Sub 

Private Sub RunServer() 
    ' Move your code from Form1_Load here, but when updating the UI, 
    ' use something like: 
    Me.Invoke(Sub() TextBox1.Text = "Waiting For connections") 
End Sub 
관련 문제