Imports System Imports System.Net Imports System.Net.Sockets Imports System.IO Imports Microsoft.VisualBasic Imports System.Text Imports System.Threading '-------- The following code is a modified version of a VB sample code "NetworkStreamSampleVBReceiver". --------' '---------------- The orginal script was downloaded from www.winsocketdotnetworkprogramming.com ----------------' '------------ The name of the process has changed from "NetworkStreamSampleVBReceiver" to SWAsrvapp ------------' ' This sample demonstrates how To use the NetworkStream Class To ' perform IO between 2 sockets. When using TCP Sockets you have to ' build a listening Socket application that will receive a connection ' from another application. In Socket terminology the application that ' receives a connection is know as a server and the peer that connects ' to a server is know as a client. ' ' The focus of this sample is not on Sockets but on network streams. We ' call this application a NetworkStreamServer because it is designed to ' receive a Socket connection and perform IO using a NetworkStream. ' ' To run this sample, simply just run the program without parameters and ' it will listen for a client connection on TCP PortOUT 5150. If you want to ' use a different PortOUT than 5150 then you can optionally supply a command ' line parameter "/PortOUT " and the listening socket will use ' your PortOUT instead. Module Module1 ' Count the packet number (MODIFIED) Public INpkcounter As Integer = 1 '(MODIFIED) Public ConnectionSocket As Socket = Nothing Public ListeningSocket As Socket = Nothing ' Let's create a network stream to communicate over the connected Socket. Public DataStreamer As NetworkStream = Nothing ' Parse command line arguments if any Public arguments() As String = Environment.GetCommandLineArgs() Public ServerIP As String = arguments(2) ' "0.0.0.0" '"127.0.0.1" Public ServerPortNo As String = arguments(3) ' 12346 Public BytesReadIN As Integer = 0 Public ReadBufferIN(1024 * 1024 * 5) As Byte Public BytestotextIN As String = "" Public INcapturetimedate As Date = System.DateTime.UtcNow Public dtime = (System.DateTime.UtcNow - INcapturetimedate) Public INcapturefileName As String = "Data\Recent\IncomingSWAdata_" + System.DateTime.UtcNow.ToString("yyyyMMddTHHmmssZ") + ".dat" Public INcaptureTXTfileName As String = "Data\Recent\IncomingSWAdata_" + System.DateTime.UtcNow.ToString("yyyyMMddTHHmmssZ") + ".txt" ' For SIIS text stream Public reporttext As StreamWriter = My.Computer.FileSystem.OpenTextFileWriter("Reports\Recent\SWA_DataRecorder_Report_" + System.DateTime.UtcNow.ToString("yyyyMMddTHHmmssZ") + ".txt", False, System.Text.Encoding.ASCII) Dim FStream_create_status As Boolean = False ' The main entry point for the application. Sub Main() reporttext.AutoFlush = True Console.Title = "SWA Data Recorder" Console.ForegroundColor = ConsoleColor.White Socket_connetor() If arguments(1) = "-server" Then If ListeningSocket.Connected = False Then Thread.Sleep(10000) reporttext.Close() Exit Sub End If End If If ConnectionSocket.Connected = False Then Thread.Sleep(10000) reporttext.Close() Exit Sub End If Do incomingtoSockIN() If BytesReadIN = 0 Then DataStreamer.Close() If arguments(1) = "-client" Then ConnectionSocket.Close() If arguments(1) = "-server" Then ListeningSocket.Close() Thread.Sleep(2000) Exit Do End If INpkcounter += 1 Loop Console.ForegroundColor = ConsoleColor.White End Sub Sub Socket_connetor() Try If arguments(1) = "-server" Then Try ' Setup a listening Socket to await a connection from a peer socket. ListeningSocket = New Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.IP) Dim ListeningEndPoint As IPEndPoint = New IPEndPoint(IPAddress.Parse(ServerIP), Convert.ToInt16(ServerPortNo)) ListeningSocket.Bind(ListeningEndPoint) Console.ForegroundColor = ConsoleColor.DarkGreen '(MODIFIED) Console.WriteLine("Bind is OK...") '(MODIFIED) reporttext.WriteLine("Bind is OK...") '(MODIFIED) ListeningSocket.Listen(5) Console.WriteLine("Listen is OK...") '(MODIFIED) reporttext.WriteLine("Listen is OK...") '(MODIFIED) Console.ForegroundColor = ConsoleColor.DarkCyan '(MODIFIED) Console.WriteLine("Awaiting a TCP INconnection on IP: " + ListeningEndPoint.Address.ToString() + " Port: " + ListeningEndPoint.Port.ToString() + "...") reporttext.WriteLine("Awaiting a TCP INconnection on IP: " + ListeningEndPoint.Address.ToString() + " Port: " + ListeningEndPoint.Port.ToString() + "...") 'Console.WriteLine("Please run your analysis client program, I'm waiting...") '(MODIFIED) ConnectionSocket = ListeningSocket.Accept() Console.ForegroundColor = ConsoleColor.DarkGreen '(MODIFIED) Console.WriteLine("Accept is OK") '(MODIFIED) reporttext.WriteLine("Accept is OK") '(MODIFIED) Dim ipIN As IPEndPoint = ConnectionSocket.RemoteEndPoint '(MODIFIED) Console.ForegroundColor = ConsoleColor.DarkCyan '(MODIFIED) Console.WriteLine("Received an connection from IPaddress: " + CStr(ipIN.Address.ToString) + " on Port No.: " + CStr(ipIN.Port)) '(MODIFIED) reporttext.WriteLine("Received an connection from IPaddress: " + CStr(ipIN.Address.ToString) + " on Port No.: " + CStr(ipIN.Port)) '(MODIFIED) Catch e As SocketException Console.ForegroundColor = ConsoleColor.DarkRed '(MODIFIED) Console.WriteLine("Failure to create Sockets: " + e.Message) reporttext.WriteLine("Failure to create Sockets: " + e.Message) reporttext.Close() Exit Sub Finally ' Close the listening socket - we do not plan to handle any ' additional connections. ListeningSocket.Close() End Try ElseIf arguments(1) = "-client" Then Try ' Let's connect to a listening server Try ConnectionSocket = New Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.IP) Console.WriteLine("Ready to connect to the server...") reporttext.WriteLine("Ready to connect to the server...") Catch e As Exception Throw New Exception("Client socket failed" + e.Message) End Try Dim ServerEndPoint As IPEndPoint = New IPEndPoint(IPAddress.Parse(ServerIP), Convert.ToInt16(ServerPortNo)) Try ConnectionSocket.Connect(ServerEndPoint) Console.ForegroundColor = ConsoleColor.DarkCyan '(MODIFIED) 'Console.WriteLine("Connected to IPaddress: " + ServerIP + " on Port No.: " + Convert.ToInt16(ServerPortNo)) '(MODIFIED) Catch e As Exception Throw New Exception("Connection to the server failed: " + e.Message) End Try Catch e As Exception Console.WriteLine(e.Message) reporttext.WriteLine(e.Message) ConnectionSocket.Close() reporttext.Close() Exit Sub End Try End If Catch e As System.IndexOutOfRangeException Console.WriteLine("Usage: Receiver [-server -client] [IP] [Port]") reporttext.WriteLine("Usage: Receiver [-server -client] [IP] [Port]") reporttext.Close() Exit Sub End Try Try ' Setup a network stream on the server Socket Console.ForegroundColor = ConsoleColor.White '(MODIFIED) Console.WriteLine(" ") Console.WriteLine("----------------------------------------------------------------------------------------------------") Console.Write(" Pktsize" & vbTab & "PktNo") Console.ForegroundColor = ConsoleColor.Cyan Console.Write(vbTab & "PktArrival DateTime(UTC)") Console.ForegroundColor = ConsoleColor.Yellow Console.WriteLine(vbTab & "Saved as (Filename)" & vbTab & "Current Filesize") Console.ForegroundColor = ConsoleColor.White Console.WriteLine("----------------------------------------------------------------------------------------------------") Console.WriteLine("") reporttext.WriteLine(" ") reporttext.WriteLine("----------------------------------------------------------------------------------------------------") reporttext.Write(" Pktsize" & vbTab & "PktNo") reporttext.Write(vbTab & "PktArrival DateTime(UTC)") reporttext.WriteLine(vbTab & "Saved as (Filename)" & vbTab & "Current Filesize") reporttext.WriteLine("----------------------------------------------------------------------------------------------------") reporttext.WriteLine("") DataStreamer = New NetworkStream(ConnectionSocket, True) Catch e As Exception Console.ForegroundColor = ConsoleColor.DarkRed '(MODIFIED) Throw New Exception("Failed to create a Network Stream with error: " + e.Message) End Try End Sub Sub incomingtoSockIN() Try Try Console.ForegroundColor = ConsoleColor.White '(MODIFIED) 'Do Dim ReadBufferIN(1024 * 1024 * 5) As Byte BytesReadIN = DataStreamer.Read(ReadBufferIN, 0, ReadBufferIN.GetUpperBound(0)) Console.Write(" " + BytesReadIN.ToString()) reporttext.Write(" " + BytesReadIN.ToString()) 'Console.Write("Recieving packets of " + BytesReadIN.ToString() + " byte(s), ") 'Console.WriteLine("") 'Console.WriteLine("ReadBufferIN length: " + ReadBufferIN.Length.ToString) ' Console.WriteLine("ReadBufferIN.GetUpperBound(0) size:" + CStr(ReadBufferIN.GetUpperBound(0))) '''''' For i = 0 To BytesReadIN - 1 ''''''BytestotextIN += ChrW(CInt(ReadBufferIN(i).ToString())) ''''''Next 'Loop Until BytesReadIN > 0 ''''''Console.WriteLine(BytestotextIN) ''''''BytestotextIN = "" FStream_appendwrite(ReadBufferIN) Catch e As Exception Console.ForegroundColor = ConsoleColor.Red BytesReadIN = 0 Console.WriteLine(e.Message) reporttext.WriteLine(e.Message) reporttext.Close() Exit Sub End Try Catch e As Exception Console.ForegroundColor = ConsoleColor.DarkRed Console.WriteLine(e.Message) reporttext.WriteLine(e.Message) Finally ' We are finished with the NetworkStream, so we will close it. ' Note: the ServerSocket will be closed by the NetworkStream. '''''''''''''''''''''''''''''''''DataStreamer.Close() '''''''''''''''''''''''''''''''''ListeningSocket.Close() End Try End Sub '--------------------------------------------------------------------------------------------------------------------------------------------------' '-------- This part of the code was copy pasted from https://msdn.microsoft.com/en-us/library/system.io.filestream.writebyte(v=vs.110).aspx--------' Sub FStream_create() Dim INcapturefileStream As FileStream = New FileStream(INcapturefileName, FileMode.Create) INcapturefileStream.Close() If arguments(1) = "-server" Then Dim INcaptureTXTfileStream As FileStream = New FileStream(INcaptureTXTfileName, FileMode.Create) INcaptureTXTfileStream.Close() End If End Sub Sub FStream_appendwrite(ReadBufferIN) If FStream_create_status = False Then FStream_create() FStream_create_status = True End If Dim INcapturefileStream = New FileStream(INcapturefileName, FileMode.Append, FileAccess.Write, FileShare.ReadWrite) Try ' Write the data to the file, byte by byte converting to binary. 'For i As Integer = 0 To BytesReadIN - 1 'INcapturefileStream.WriteByte(ReadBufferIN) ' Next i INcapturefileStream.Write(ReadBufferIN, 0, BytesReadIN) ' Set the stream position to the beginning of the stream. 'INcapturefileStream.Seek(0, SeekOrigin.Begin) Console.Write(vbTab & CStr(INpkcounter)) Console.ForegroundColor = ConsoleColor.Cyan Console.Write(vbTab & System.DateTime.UtcNow.ToString("yyyy/MM/dd HH:mm:ss")) Console.ForegroundColor = ConsoleColor.Yellow Console.Write(vbTab & vbTab & Right(INcapturefileStream.Name, 20)) Console.WriteLine(vbTab & INcapturefileStream.Length) reporttext.Write(vbTab & CStr(INpkcounter)) reporttext.Write(vbTab & System.DateTime.UtcNow.ToString("yyyy/MM/dd HH:mm:ss")) reporttext.Write(vbTab & vbTab & Right(INcapturefileStream.Name, 20)) reporttext.WriteLine(vbTab & INcapturefileStream.Length) dtime = (System.DateTime.UtcNow - INcapturetimedate) If INcapturefileStream.Length >= (104857600 / 20) Then '5MB INcapturefileStream.Close() If dtime.TotalMinutes >= 1 Then 'Preventing from overwriting with same filename. INcapturefileName = "Data\Recent\IncomingSWAdata_" + System.DateTime.UtcNow.ToString("yyyyMMddTHHmmssZ") + ".dat" INcapturetimedate = System.DateTime.UtcNow Else Thread.Sleep(1100) INcapturefileName = "Data\Recent\IncomingSWAdata_" + System.DateTime.UtcNow.ToString("yyyyMMddTHHmmssZ") + ".dat" INcapturetimedate = System.DateTime.UtcNow End If FStream_create() Exit Try End If dtime = (System.DateTime.UtcNow - INcapturetimedate) If dtime.TotalMinutes >= 5 Then '5 minutes INcapturefileStream.Close() INcapturefileName = "Data\Recent\IncomingSWAdata_" + System.DateTime.UtcNow.ToString("yyyyMMddTHHmmssZ") + ".dat" INcapturetimedate = System.DateTime.UtcNow FStream_create() Exit Try End If Finally INcapturefileStream.Close() End Try If arguments(1) = "-server" Then Dim INcaptureTXTfileStream = New FileStream(INcaptureTXTfileName, FileMode.Append, FileAccess.Write, FileShare.ReadWrite) Try ' Write the data to the file, byte by byte as it comes out from SIIS (Ascii hex) Dim asciihextoint As Integer For i As Integer = 0 To BytesReadIN - 1 Try asciihextoint = Convert.ToInt32(ChrW(CInt(ReadBufferIN(i).ToString())) + ChrW(CInt(ReadBufferIN(i + 1).ToString())), 16) INcaptureTXTfileStream.WriteByte(Convert.ToByte(asciihextoint)) i += 1 Catch e As Exception End Try Next i If INcaptureTXTfileStream.Length >= (104857600 / 20) Then '5MB INcaptureTXTfileStream.Close() INcaptureTXTfileName = "Data\Recent\IncomingSWAdata_" + System.DateTime.UtcNow.ToString("yyyyMMddTHHmmssZ") + ".txt" FStream_create() Exit Try End If Finally INcaptureTXTfileStream.Close() End Try End If End Sub '--------------------------------------------------------------------------------------------------------------------------------------------------' '--------------------------------------------------------------------------------------------------------------------------------------------------' End Module