将数据从socketcommunication传递到用户界面

时间:2013-06-23 20:38:08

标签: vb.net sockets

在我当前的项目中,我正在向/从serversocket / clientsocket(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中的其他内容?

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

1 个答案:

答案 0 :(得分: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