0

在我当前的项目中,我正在向/从服务器套接字/客户端套接字 (TCP) 发送和接收文本消息,就像聊天一样(我的项目是用 VB.NET 编写的)。只要我将发送的字节转换为字符串并将它们呈现在 msgbox() 中,它就可以工作。此代码处理该部分:

Try
    client = ar.AsyncState
    client.EndReceive(ar)
    client.BeginReceive(bytes2, 0, bytes2.Length, SocketFlags.None, New AsyncCallback(AddressOf OnRecieve), client)
    Try
        Dim message As String = System.Text.ASCIIEncoding.ASCII.GetString(bytes2)
        MsgBox(message)
        Array.Clear(bytes2, bytes2.GetLowerBound(0), bytes2.Length)
    Catch ex As Exception
        MsgBox("Error writing received message")
    End Try
 Catch ex As Exception
    MsgBox("Error receiving message from server")
 End Try

到目前为止,一切都很好。但是,当我尝试将“MsgBox(message)”更改为 label1.text = message 时,我收到错误消息:“写入收到的消息时出错”。那么,我的问题是为什么会发生这种情况,我可以做些什么来纠正它,以便我可以让我的套接字接收可以添加到 UI 中的文本框和其他内容的信息?

提前感谢您提供的任何帮助

4

1 回答 1

0

使用委托和 BeginInvoke() 正确编组对主 UI 线程的调用:

Private Sub OnRecieve(ar As IAsyncResult)
    Try
        client = ar.AsyncState
        client.EndReceive(ar)

        Try
            Dim message As String = System.Text.ASCIIEncoding.ASCII.GetString(bytes2)
            NewMessage(message)
        Catch ex As Exception
            MsgBox("Error writing received message")
        Finally
            Array.Clear(bytes2, bytes2.GetLowerBound(0), bytes2.Length)
        End Try

        client.BeginReceive(bytes2, 0, bytes2.Length, SocketFlags.None, New AsyncCallback(AddressOf OnRecieve), client)
    Catch ex As Exception
        MsgBox("Error receiving message from server")
    End Try
End Sub

Private Delegate Sub MessageDelegate(ByVal msg As String)

Private Sub NewMessage(ByVal msg As String)
    If Me.InvokeRequired Then
        Me.BeginInvoke(New MessageDelegate(AddressOf NewMessage), New Object() {msg})
    Else
        Label1.Text = msg
    End If
End Sub
于 2013-06-23T21:17:25.183 回答