强制使用TcpClient运行代码

时间:2015-12-04 15:58:51

标签: tcpclient netstream

我正在为一些运行Windows CE 5的条形码扫描仪编写一些软件。

软件需要与服务器通信并获取数据。 它使用TcpClient连接到在单独计算机上运行的某些软件。

当它将数据发送到服务器软件时,服务器软件会发回一条消息,说“已接收##字节 - ”和发送的命令,因此我可以澄清该命令已被正确接收(这是因为我遇到了一个问题,即字符串被“混淆”了)

当条形码扫描器收到响应时,我希望它等待另一个带有命令结果的响应。

我遇到的问题是,当TcpClient接收数据时,它调用名为ReceivingMessage的Sub,但只有在发送消息的sub完成后才会执行此操作。

SendMessage功能如下

Public Function SendMessage(ByVal SendString As String) As Boolean
    Dim _Result As Boolean = False
    Dim _SendString As String = ""

    Try
        _Response = ""

        If Not _Connection Is Nothing AndAlso _Connection.Client.Client.Connected AndAlso Not _Connection.Stream Is Nothing Then
            Dim _Now As String = Format(CInt(Now.Day), "00") & "/" & Format(CInt(Now.Month), "00") & "/" & Format(CInt(Now.Year), "0000") & " " & Format(CInt(Now.Hour), "00") & ":" & Format(CInt(Now.Minute), "00") & ":" & Format(CInt(Now.Second), "00")

            _SendString = _Now & CmdSpcr & SendString & EndOfMessageString

            Dim buffer() As Byte = System.Text.Encoding.ASCII.GetBytes(_SendString)

            _Connection.Stream.Write(buffer, 0, buffer.Length)

            _Result = True
        End If

        _WaitingForResponse = True

        'Wait for a response here

        If _Response.StartsWith("Received ") And _Response.EndsWith(" Bytes - " & _SendString) Then
            _Result = True
        Else
            _Result = False
        End If
    Catch ex As Exception
        RaiseEvent DisplayMessage(ex.ToString, MsgBoxStyle.Critical, "Error")
        _Result = False
    End Try

    Return _Result
End Function

ReceivingMessage子很简单,被称为另一个类的一部分

Private Sub ReceivingMessage(ByVal message As String)
    If _WaitingForResponse Then
        _Response = message
    Else
        RaiseEvent MessageReceived(message)
    End If
End Sub

这是班级

Imports System.Net.Sockets
Imports System.Net

Public Class modConnectionInfo
    Private _ReceivingMessageMethod As Action(Of String)
    Private _Buffer(9999) As Byte
    Private _Client As TcpClient
    Private _LastReadLength As Integer
    Private _Stream As NetworkStream

    Public ReadOnly Property ReceivingMessageMethod() As Action(Of String)
        Get
            Return _ReceivingMessageMethod
        End Get
    End Property

    Public ReadOnly Property Client() As TcpClient
        Get
            Return _Client
        End Get
    End Property

    Public ReadOnly Property Stream() As NetworkStream
        Get
            Return _Stream
        End Get
    End Property

    Public ReadOnly Property LastReadLength() As Integer
        Get
            Return _LastReadLength
        End Get
    End Property

    Public Sub AwaitData()
        _Stream.BeginRead(_Buffer, 0, _Buffer.Length, AddressOf DoReadData, Me)
    End Sub

    Public Sub Close()
        If _Client IsNot Nothing Then _Client.Close()

        _Client = Nothing
        _Stream = Nothing
    End Sub

    Private Sub DoReadData(ByVal result As IAsyncResult)
        Dim info As modConnectionInfo = CType(result.AsyncState, modConnectionInfo)

        Try
            If info._Stream IsNot Nothing AndAlso info._Stream.CanRead Then
                info._LastReadLength = info._Stream.EndRead(result)

                If info._LastReadLength > 0 Then
                    Dim message As String = System.Text.Encoding.ASCII.GetString(info._Buffer, 0, info._Buffer.Count)
                    message = message.Replace(vbNullChar, "")
                    info._ReceivingMessageMethod(message)
                End If

                ReDim info._Buffer(9999)
                info.AwaitData()
            End If
        Catch ex As Exception
            info._LastReadLength = -1
            info._ReceivingMessageMethod(ex.Message)
        End Try
    End Sub

    Public Sub New(ByVal address As IPAddress, ByVal port As Integer, ByVal ReceivingMessage As Action(Of String))
        _ReceivingMessageMethod = ReceivingMessage
        _Client = New TcpClient
        _Client.Connect(address, port)
        _Stream = _Client.GetStream
    End Sub
End Class

有没有人知道如何让SendMessage子在我放置“'等待响应”的部分暂停,并允许ReceivingMessage子在继续之前运行?

调用此类的方式如下

_Connection = New modConnectionInfo(IPAddress.Parse(ServerIP), CInt(ServerPort), AddressOf ReceivingMessage)

If _Connection.Client.Client.Connected Then
    _Connected = True
End If

_Connection.AwaitData()

非常感谢任何帮助

0 个答案:

没有答案