我的VB.NET服务器/客户端聊天应用程序出了问题。
当我从客户端应用程序向服务器应用程序发送一些信息时,会出现问题。我成功建立了连接并发送了一条消息,但它没有显示该消息,而是显示了我的表单服务器的名称。
Public Class Form1
Private Server As TCPControl
Private Sub Form1_FormClosing(ByVal sender As Object, ByVal e As System.Windows.Forms.FormClosingEventArgs) Handles Me.FormClosing
Server.IsListening = False
End Sub
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
Server = New TCPControl ' fires new sub
txtChat.Text = " :: SERVER STARTED :: " & vbCrLf
AddHandler Server.MessageRecived, AddressOf OnLineRecived
End Sub
'da se uspijesno prenesu informacije na kontrolu
Private Delegate Sub UpdateTextDelegate(ByVal tb As TextBox, ByVal txt As String)
'UPDATE TEXTBOX
Private Sub UpdateText(ByVal tb As TextBox, ByVal txt As String)
If tb.InvokeRequired Then 'HERE I SEE MY MESSAGE FROM CLIENT APLICATION
tb.Invoke(New UpdateTextDelegate(AddressOf UpdateText), New Object() {tb, txt})
Else
If txt IsNot Nothing Then tb.AppendText(Text & vbCrLf)
End If
End Sub
Private Sub OnLineRecived(ByVal sender As TCPControl, ByVal data As String)
UpdateText(txtChat, data) 'HERE I SEE MY MESSAGE FROM CLIENT APLICATION
End Sub
End Class
Public Class TCPControl
Public Event MessageRecived(ByVal sender As TCPControl, ByVal data As String)
'SERVER CONFIG
Public ServerIp As IPAddress = IPAddress.Parse("192.168.1.108")
Public ServerPort As Integer = 46555
Public Server As TcpListener
Private CommThread As Thread
Public IsListening As Boolean = True
'CLIENTS (samo ce prihvatiti jednog klijenta)
Private Client As TcpClient
Private ClientData As StreamReader
Public Sub New()
Server = New TcpListener(ServerIp, ServerPort)
Server.Start()
CommThread = New Thread(New ThreadStart(AddressOf Listening))
CommThread.Start()
End Sub
Private Sub Listening()
' CREATE LISTENAR LOOP
Do Until IsListening = False
' ACCEPT INCOMING CONNECTIONS
If Server.Pending = True Then
Client = Server.AcceptTcpClient
ClientData = New StreamReader(Client.GetStream)
End If
'RAISE EVANT FOR INCOMING MESSAGES
Try
RaiseEvent MessageRecived(Me, ClientData.ReadLine) ' now is displying the name of server form
Catch ex As Exception
End Try
'REDUCE CPU USAGE
Thread.Sleep(100)
Loop
End Sub
End Class
答案 0 :(得分:1)
在UpdateText
上更新客户端TextBox时出错。
If tb.InvokeRequired Then
tb.Invoke(New UpdateTextDelegate(AddressOf UpdateText), New Object() {tb, txt})
Else
If txt IsNot Nothing Then tb.AppendText(Text & vbCrLf) ' Here
End If
使用Text
更改txt
。
If txt IsNot Nothing Then tb.AppendText(txt & vbCrLf)