#2
xyxcc1772018-04-08 14:24
|
请求各位大神帮忙解决下,为什么建立好了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