我在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 :(得分: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