我正在编写一个vb.net应用程序,用于从以太网设备接收数据并将该数据存储在文本文件中。有没有办法只在从设备发送数据时才启动函数?
例如,
Public Sub Main()
'This should run only when data is received from the device
end sub
这是我的代码:
Imports System
Imports System.Net
Imports System.Net.Sockets
Imports System.Text
Imports System.IO
Public Class Form1
'Data buffer for incoming data.
Dim bytes(1024) As Byte
Dim remoteEP As New IPEndPoint(IPAddress.Parse("169.254.244.11"), 10051)
'Create a TCP/IP socket.
Dim sender As New Socket(AddressFamily.InterNetwork, _
SocketType.Stream, ProtocolType.Tcp)
Public Sub Main()
'Connect the socket to the remote endpoint.
sender.Connect(remoteEP)
Dim bytesRec2, time_date
time_date = Date.Now.ToString("dd-MM-yyyy-hh-mm-ss")
Dim filepath As String = "hexfiles/" & time_date + ".hex"
If Not System.IO.File.Exists(filepath) Then
System.IO.File.Create(filepath).Dispose()
End If
Dim text_data
While (True)
bytesRec2 = sender.Receive(bytes)
text_data = System.Text.Encoding.ASCII.GetString(bytes, 0, bytesRec2)
ByteArrayToFile(filepath, GetByteArray(bytes, 0, bytesRec2))
If text_data.IndexOf("CALL END") >= 0 Then
Dim newFilePath As String = filepath.Replace(".hex", ".mp3")
System.IO.File.Move(filepath, newFilePath)
sender.Disconnect(1)
Exit Sub
End If
End While
End Sub
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
Call Main()
End Sub
Private Function GetFileContents(ByVal file_name As String) As String
Dim stream_reader As New IO.StreamReader(file_name)
Dim txt As String = stream_reader.ReadToEnd()
stream_reader.Close()
Return txt
End Function
Private Function GetByteArray(ByVal MyArray As System.Array, ByVal Start As Integer, ByVal Length As Integer) As Byte()
Dim ReturnValue(Length - 1) As Byte
Array.ConstrainedCopy(MyArray, Start, ReturnValue, 0, Length)
Return ReturnValue
End Function
Public Function ByteArrayToFile(ByVal _FileName As String, ByVal _ByteArray() As Byte) As Boolean
Try
' Open file for reading
Dim _FileStream As New System.IO.FileStream(_FileName, System.IO.FileMode.Append, System.IO.FileAccess.Write)
' Writes a block of bytes to this stream using data from a byte array.
_FileStream.Write(_ByteArray, 0, _ByteArray.Length)
' close file stream
_FileStream.Close()
Return True
Catch _Exception As Exception
' Error
Console.WriteLine("Exception caught in process: {0}", _Exception.ToString())
End Try
End Function
End Class