注册 登录
编程论坛 VB.NET论坛

建立好的socket连接,为什么接收不到数据

做自己就好 发布于 2018-04-07 18:36, 5197 次点击
   请求各位大神帮忙解决下,为什么建立好了socket连接之后,无法接收到客户端传来的数据啊。客户端是用GPRS模块和单片机相连接的移动终端,具体代码如下(过程变量和空间都已声明):
 Public Sub Listen()
        Try
            tlTcpListen = New TcpListener(iPort) '以定义的端口号来初始化TcpListener实例
            tlTcpListen.Start() '开始监听
            ToolStripStatusLabel1.Text = "正在监听..."
            skSocket = tlTcpListen.AcceptSocket() '通过TCP连接请求
            time0 = False
            Dim temteep As EndPoint = skSocket.RemoteEndPoint
            Dim tempeip As IPEndPoint = DirectCast(temteep, IPEndPoint)
            ToolStripStatusLabel1.Text = "已经建立TCP连接!"

            '循环侦听
            While blistener
                Dim stream() As Byte = New Byte(4000) {}
                Dim i As Integer = skSocket.ReceiveFrom(stream, temteep)
                'Dim t As New UpDataUI(AddressOf dataprocess)
                'Me.Invoke(t, stream, i)
                If (time0) Then
                    dataprocess(stream, i)
                    message0 = message0 + 1
                End If
                ListBox1.Items.Insert(0, Encoding.Unicode.GetString(stream))
            End While
        Catch ex As System.Security.SecurityException
            MessageBox.Show("侦听失败!", "错误")
        End Try
    End Sub
  '对电机转速和电流信号分别存入对应的数组中
    Private Sub dataprocess(stream As Byte(), length As Byte)

        If length Mod 2 = 0 Then '判断数据是否有效,只有当是字时,才能进行下一步处理
            Try
                For i = 0 To length - 4 Step 5 '6个数为一组
                    Dim value1 As Int16 = (stream(i) And &HFF) * 256 + stream(i + 1)  '得到16位有符号整数,不改变其值的大小
                    Dim value2 As Int16 = (value1 And &HFF) * 256 + stream(i + 2)
                    Dim valuen As Int32 = (value2 And &HFFFF) * 256 + stream(i + 3) '得到32位有符号整数
                    ReDim Preserve out0(out0.Length) '重新定义数组大小且使之前已赋值的数不被清空
                    out0(out0.Length - 1) = valuen '把转速数据存到原有的数据后一位
                    '对数组求平均值,使绘图的时候曲线更平滑


                    Dim valueI As Byte = (stream(i + 4) And &HFF)
                    ReDim Preserve out1(out1.Length)
                    out1(out1.Length - 1) = valueI '把电流数据存到原有的数据后一位

                Next
            Catch ex As Exception

            End Try
        End If
    End Sub
4 回复
#2
xyxcc1772018-04-08 14:24
If (time0) Then
time0什么时候是True呢?
#3
jyzas2018-08-25 22:58
楼主,问题解决了没有??共享下
#4
moou2018-08-28 16:03
                If (time0) Then
                    dataprocess(stream, i)
                    message0 = message0 + 1
                End If


这个time0 你直接定义为False 没看到你的程序里什么时候能把它变成True
#5
cmhchu2018-09-25 21:46
楼主的问题解决了么,最近正准备使用socket,好多问题想跟楼主交流
1