⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 receive.vb

📁 计算机通信MC35接收软件
💻 VB
字号:
Imports System
Imports System.Net
Imports System.Net.Sockets
Imports System.Threading
Imports System.Text

Module Module1
    '得到本地主机信息
    Public ipHostInfo As IPHostEntry = Dns.Resolve(Dns.GetHostName())
    '本地ip地址
    Public LocalIP As IPAddress = ipHostInfo.AddressList(0)
    '本地EP
    Public LocalEP As New IPEndPoint(LocalIP, 60000)

    Public Class stateobject

        '远程主机ip
        Public RemoteIP As IPAddress
        '远端主机端口
        Public RemotePort As Integer
        '远程主机EP
        Public RemoteEP As IPEndPoint
        '接收缓冲区大小,与最大帧长度相同
        Public Const BufferSize As Integer = 130
        '接收缓冲区
        Public buffer(BufferSize) As Byte
        'client socket
        Public workSocket As Socket
    End Class  'stateobject


    Public Class SocketListen
     
        ' Thread signal.
        Public Shared allDone As New ManualResetEvent(False)
        '事件,数据接收完毕
        Public Shared Event DataRecComplete()

        Public Shared Sub StartListening()
            ' Data buffer for incoming data
            'Dim Byt_bytes() As Byte = New [Byte](1024) {}
            ' Intializes a TCP/IP socket
            Dim Sck_listener As New Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)
            ' Bind the socket to the local endpoint and listen for incoming connections
            Try
                Sck_listener.Bind(LocalEP)
                Sck_listener.Listen(16)

                While True
                    ' Set the event to nonsignaled state
                    allDone.Reset()
                    ' Start an asynchronous socket to listen for connections
                    Console.WriteLine("Waiting for a connection...")

                    Sck_listener.BeginAccept(New AsyncCallback(AddressOf AcceptCallback), Sck_listener)
                    'Console.WriteLine("connect done")
                    ' Wait until a connection is made before continuing
                    allDone.WaitOne()
                End While

            Catch e As Exception
                Console.WriteLine(e.ToString())
            End Try
            Console.WriteLine(ControlChars.Cr + "connection closed.")
        End Sub  'StartListen

        Public Shared Sub AcceptCallback(ByVal ar As IAsyncResult)
            ' Signal the main thread to continue.
            'Console.WriteLine("before alldone.set")
            'allDone.Set() '多线程

            'Console.WriteLine("after alldone.set")

            ' Get the socket that handles the client request.

            Dim listener As Socket = CType(ar.AsyncState, Socket)

            Dim handler As Socket = listener.EndAccept(ar)


            ' Create the state object.
            Dim state As New stateobject
            state.workSocket = handler

            '远端主机信息
            state.RemoteEP = handler.RemoteEndPoint
            state.RemoteIP = state.RemoteEP.Address
            state.RemotePort = state.RemoteEP.Port

            Console.WriteLine("建立与远端主机:" & state.RemoteIP.ToString & ":" & state.RemotePort.ToString & " 的连接")

           

            handler.BeginReceive(state.buffer, 0, stateobject.BufferSize, 0, New AsyncCallback(AddressOf ReadCallback), state)
        End Sub 'AcceptCallback

        Public Shared Sub ReadCallback(ByVal ar As IAsyncResult)
            Dim content As String

            ' Retrieve the state object and the handler socket
            ' from the asynchronous state object.
            Dim state As stateobject = CType(ar.AsyncState, stateobject)
            Dim handler As Socket = state.workSocket

            '''''''''''''''
            Dim bytesRead As Integer
            Try
                bytesRead = handler.EndReceive(ar)
            Catch ex As Exception
                Exit Sub
            End Try
            ' Read data from client socket. 


            If bytesRead > 0 Then

                ' Received data string
                Dim sb As New StringBuilder
                sb.Append(Encoding.ASCII.GetString(state.buffer, 0, bytesRead))
                content = sb.ToString()
                Console.WriteLine(content)

                '数据帧里有*,表示传输结束
                If content.IndexOf("*") > -1 Then

                    Console.WriteLine("there is a * founded!!!")

                    ' 对收到的数据进行处理
                    Check(state.buffer, bytesRead, state) 'check the data received

                    handler.Shutdown(SocketShutdown.Both)
                    handler.Close()

                    '引发事件,数据传输完成
                    RaiseEvent DataRecComplete()

                Else
                    ' Not all data received. Get more.
                    Check(state.buffer, bytesRead, state) 'check the data received

                    handler.BeginReceive(state.buffer, 0, stateobject.BufferSize, 0, New AsyncCallback(AddressOf ReadCallback), state)
                End If
            End If
        End Sub 'ReadCallback

        Private Shared Sub Check(ByVal data() As Byte, ByVal len As Integer, ByVal state As stateobject)

            '判断帧
            If data(0) = &H99 Then  'first byte is 10011001 ? 
                If data(1) = &H0 Then 'second byte is 00000000 ?
                    If data(len - 1) = &H2A Then 'last byte is 00101010(*) ? 
                        save(data, len, state) 'save received data

                    ElseIf data(len - 1) = &HAA Then 'or last bye is 10101010 ? 
                        save(data, len, state) 'save received data

                    Else : Exit Sub
                    End If

                Else : Exit Sub
                End If

            Else : Exit Sub
            End If

        End Sub 'Send

        Private Shared Sub save(ByVal data() As Byte, ByVal len As Integer, ByVal state As stateobject)


            If data(2) = &H1 Then '子站注册帧

                '子站id
                Dim id As Integer
                id = data(3) + data(4) * 10

                '子站socket
                Dim ip As IPAddress
                Dim port As Integer
                ip = state.RemoteIP
                port = state.RemotePort
                Try
                    '存数据库子站信息
                    regist(id, ip.ToString, port.ToString)
                Catch ex As Exception
                    Exit Sub
                End Try
                

                allDone.Set() '单线程

            ElseIf data(2) = &H2 Then '子站上传的数据帧

                '子站id
                Dim id As Integer
                id = data(3) + data(4) * 10

                '时间
                Dim year, month, day As Integer
                year = data(5) + data(6) * 10 + 2000
                month = data(7) + data(8) * 10
                day = data(9) + data(10) * 10
                Dim hour, minute, second As Integer
                hour = data(11) + data(12) * 10
                minute = data(13) + data(14) * 10
                second = data(15) + data(16) * 10
                Dim info As New System.Globalization.CultureInfo("zh-CN", False)
                Dim cal As System.Globalization.Calendar
                cal = info.Calendar

                Dim date_time As New DateTime(year, month, day, hour, minute, second, 0, cal)
                Dim datetime_str As String = date_time.ToString '字符串形式的日期和时间 2003-6-2 9:10:10

                '数据
                Dim i, j, m As Integer
                Dim k As Int64
                Dim float(16) As Single
                '将数据存入一个single数组中
                For i = 0 To 15
                    k = 1
                    m = 0
                    For j = 0 To 6

                        float(i) = float(i) + data(17 + j + m) * 0.0001 * k
                        k = k * 10
                    Next
                    m = m + 7
                Next
                Dim index(16) As Integer
                For i = 0 To 15
                    If float(i) > 1000.0 Then
                        index(i) = 0
                    Else : index(i) = 1
                    End If
                Next
                Try
                    '向数据库中存数据
                    updata(id, datetime_str, index, float)
                Catch ex As Exception
                    Exit Sub
                End Try

                allDone.Set() '单线程

            Else : Exit Sub '帧类型没定义,退出
            End If

        End Sub 'save 

        Public Shared Sub regist(ByVal id As Integer, ByVal ip As String, ByVal port As String)

        End Sub 'regist

        Public Shared Sub updata(ByVal id As Integer, ByVal datetime_str As String, ByVal index() As Integer, ByVal data() As Single)

        End Sub 'updata

        Public Shared Sub main()
            MsgBox("本地IP地址为 " & LocalIP.ToString & Chr(13) & "通信端口为60000", MsgBoxStyle.OKOnly Or MsgBoxStyle.Information, "通信信息")

            Dim info As New System.Globalization.CultureInfo("zh-CN", False)
            Dim cal As System.Globalization.Calendar
            cal = info.Calendar
            Dim date_time As New DateTime(2003, 6, 2, 21, 10, 10, 0, cal)
            Dim datetime_str As String = date_time.ToString
            Console.WriteLine(datetime_str)

            Dim t As New Thread(AddressOf StartListening)
            t.Start()
            Dim id As Byte() = {&H2, &H3}
            Dim pwd As Byte() = {&H2, &H2, &H2, &H2, &H2, &H2}
            Dim s As New send("202.113.2.54", "60000", id, pwd, date_time)

        End Sub      'Main

    End Class  'SocketListen
    Public Class c
        Public Event ConnectDone()

        Public Sub Connected()
            RaiseEvent ConnectDone()
        End Sub
    End Class

End Module

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -