There's a way know when a TCP payload ends? - vb.net

I have a routine that sends data over TCP and must wait a response on the same opened socket.
The data to be receiver doesn't fit in one TCP message, so, the question is This code will wait until the last byte or should I must to add some indication at the end?
Private Function SendReport(ByVal Msg As String, ByVal Host As String, ByVal Port As String) As String
Try
Dim Tx As New TcpClient()
Dim stream As NetworkStream = Nothing
Dim CloseStream As Boolean = False
Dim LingerMode As New LingerOption(True, 5)
' String to store the response ASCII representation.
Dim responseData As [String] = [String].Empty
Tx.NoDelay = True
Tx.LingerState = LingerMode
Tx.SendTimeout = 10000
Tx.ReceiveTimeout = 10000
Tx.Connect(Host, Port)
' Translate the passed message into ASCII and store it as a Byte array.
Dim data As [Byte]() = System.Text.Encoding.ASCII.GetBytes(Msg)
' Get a client stream for reading and writing.
' Stream stream = client.GetStream();
stream = Tx.GetStream()
CloseStream = True
'stream.WriteTimeout = 100
' Send the message to the connected TcpServer.
stream.Write(data, 0, data.Length)
'Tx.Connected
' Receive the TcpServer.response.
' Buffer to store the response bytes.
data = New [Byte](256) {}
' Read the first batch of the TcpServer response bytes.
Dim bytes As Int32 = stream.Read(data, 0, data.Length)
responseData = System.Text.Encoding.ASCII.GetString(data, 0, bytes)
If CloseStream = True Then
stream.Close()
End If
Tx.Close()
Return responseData
Catch ex As Exception
WriteRTBLog(ex.Message, Color.Red)
WriteRTBLog(ex.StackTrace, Color.DarkRed)
Return "Error"
End Try
End Function
I never made an application to receive more than one TCP packet before, so I don't know what to expect.
The longer data that I must to expect is about 524KB

Related

TCP Socket doesn't send all the data

I'm trying to send about 250KBytes but I get cut at 8KBytes
I doesn't need any answer from the remote server.
I don't understand what I'm doing wrong.
Is like the tx doesn't change the outbuffer size.
Private Function SendReport7B(ByVal Msg As String, ByVal Host As String, ByVal Port As String) As String
Try
Dim Msgs() As String
Dim Tx As New TcpClient()
Dim stream As NetworkStream = Nothing
Dim LingerMode As New LingerOption(True, 1)
'Dim BSize As Integer
Tx.NoDelay = True
Tx.LingerState = LingerMode
Tx.SendTimeout = 5000
If Msg.Length > Tx.SendBufferSize Then
Tx.SendBufferSize = Msg.Length + 256
End If
Tx.Connect(Host, Port)
Msgs = Msg.Split(Chr(10))
' Translate the passed message into ASCII and store it as a Byte array.
Dim data As [Byte]() = System.Text.Encoding.ASCII.GetBytes(Msg)
' Get a client stream for reading and writing.
' Stream stream = client.GetStream();
stream = Tx.GetStream()
'stream.WriteTimeout = 100
' Send the message to the connected TcpServer.
stream.Write(data, 0, data.Length)
Tx.Close()
Return "OK" 'responseData
Catch ex As Exception
Return "Error: " & ex.Message
End Try
End Function

Looking for a Way to Loop Until value of TCP Packet = 1

I am trying to trigger a given function off of a static TCP port number. When the port number receives a packet of Value = 1 it will then trigger an internal function.
strHostName = System.Net.Dns.GetHostName()
strIPAddress = System.Net.Dns.GetHostEntry(strHostName).AddressList(0).ToString()
Dim IP As System.Net.IPAddress = System.Net.IPAddress.Parse(strIPAddress)
Dim PortNO As Integer = 5040
Dim MyData As String = ""
Dim LabView_TriggerValue As Integer = 1
Try
Dim client As TcpClient = New TcpClient(IP.ToString, PortNO)
Dim data As Byte() = New Byte(9998) {}
Dim responseData As String = String.Empty
Dim stream As NetworkStream = client.GetStream()
stream.ReadTimeout = 1000
Dim bytes As Int32 = stream.Read(data, 0, data.Length)
responseData = System.Text.Encoding.ASCII.GetString(data, 0, bytes)
MyData = responseData.Replace(vbCrLf, "")
MessageBox.Show(responseData)
'Return MyData
Do
Loop Until responseData = LabView_TriggerValue
stream.Close()
client.Close()
Catch ex As Exception
Label1.Text = "" & ex.Message
End Try
I am running into a problem where my Do...Loop Until call-out is not looping. The code runs regardless of the value on Port 5040. Ideally it should keep looping.refreshing the port 5040 until it receives a packet with value of integer = 1.

vb.net weight scale tcpip not getting data

i am new to vb.net 2008 to get data from weigh scale using tcpclient(). below mentioned code is able to connect with machine but not getting the data. But hyperterminal is able to get data.
I searched most of the post but may coding exist only for serial port connection.
Output MsgBox :
Received: {0}
Imports System.Net.Sockets
Public Sub Connect(ByVal server As [String], ByVal _Ports As Int32, ByVal message As [String])
Try
' Create a TcpClient.
' Note, for this client to work you need to have a TcpServer
' connected to the same address as specified by the server, port
' combination.
Dim port As Int32 = _Ports
Dim client As New TcpClient()
'Dim client As New TcpClient(server, port)
client.Connect(server, port)
If client.Client.Connected Then TextBox3.Text = "Connected"
' Translate the passed message into ASCII and store it as a Byte array.
Dim data As [Byte]() = System.Text.Encoding.ASCII.GetBytes(message)
' Get a client stream for reading and writing.
' Stream stream = client.GetStream();
Dim stream As NetworkStream = client.GetStream()
Dim Buffer(client.ReceiveBufferSize) As Byte
' Send the message to the connected TcpServer.
stream.Write(data, 0, data.Length)
'Console.WriteLine("Sent: {0}", message)
MsgBox("Sent: {0} " & message)
' Receive the TcpServer.response.
' Buffer to store the response bytes.
data = New [Byte](2047) {}
'MsgBox("Response Byte - " & data.Length)
' String to store the response ASCII representation.
Dim responseData As [String] = [String].Empty
' Read the first batch of the TcpServer response bytes.
Dim bytes As Int32 = stream.Read(data, 0, data.Length)
responseData = System.Text.Encoding.ASCII.GetString(data, 0, bytes)
'Console.WriteLine("Received: {0}", responseData)
MsgBox("Received: {0} " & responseData)
' Close everything.
stream.Close()
client.Close()
Catch e As ArgumentNullException
'Console.WriteLine("ArgumentNullException: {0}", e)
MsgBox("ArgumentNullException: {0}" & e.Message)
Catch e As SocketException
'Console.WriteLine("SocketException: {0}", e)
MsgBox("SocketException: {0}" & e.Message)
End Try
MsgBox("Got to this point in code")
'Console.WriteLine(ControlChars.Cr + " Press Enter to continue...")
'Console.Read()
End Sub
This:
MsgBox("Received: {0} " & responseData)
...does not automatically replace {0} with the value of responseData.
The {0} placeholder is used with the String.Format() function. Change your code to this, in all applicable places, and check the result:
' Let's also get rid of the legacy VB6 MsgBox() function:
MessageBox.Show(String.Format("Received: {0} ", responseData))
Also, what's with the square brackets around some data types (i.e. [String])? They aren't needed.

Chrome Native Messaging Host VB.Net

I have had a hard time finding any support for Chrome Native Messaging Hosts in VB.Net, after much trial and error I have put together something that works for a single message at a time. However I have not been able to get the
While OpenStandardStreamIn() IsNot Nothing
part to work. If anyone has any suggestions...
OTHERWISE THIS CODE WORKS GREAT, for anyone else like me looking for a VB.Net Native Message Host:
Also, this uses Newtonsoft.Json Lib for JSON serializing...
Imports System
Imports System.Collections.Generic
Imports System.Linq
Imports System.Text
Imports System.Threading.Tasks
Imports System.Diagnostics
Imports System.Runtime.InteropServices
Module Module1
Public Sub Main(ByVal args As String())
'create response as an array so it can be easily converted JSON
Dim ResponseString() As String = {""}
' get input from chrome extension
Dim InputString As String = OpenStandardStreamIn()
' Do whatever you want with Input, then prepare Response
ResponseString(0) = DO_SOMETHING(InputString)
' Send Response to Chrome
OpenStandardStreamOut(ResponseString)
End Sub
Public Function OpenStandardStreamIn() As String
Dim MsgLength As Integer = 0
Dim InputData As String = ""
Dim LenBytes As Byte() = New Byte(3) {} 'first 4 bytes are length
Dim StdIn As System.IO.Stream = Console.OpenStandardInput() 'open the stream
StdIn.Read(LenBytes, 0, 4) 'length
MsgLength = System.BitConverter.ToInt32(LenBytes, 0) 'convert length to Int
Dim Buffer As Char() = New Char(MsgLength - 1) {} 'create Char array for remaining bytes
Using Reader As System.IO.StreamReader = New System.IO.StreamReader(StdIn) 'Using to auto dispose of stream reader
While Reader.Peek() >= 0 'while the next byte is not Null
Reader.Read(Buffer, 0, Buffer.Length) 'add to the buffer
End While
End Using
InputData = New String(Buffer) 'convert buffer to string
Return InputData
End Function
Private Sub OpenStandardStreamOut(ByVal ResponseData() As String) 'fit the response in an array so it can be JSON'd
Dim OutputData As String = ""
Dim LenBytes As Byte() = New Byte(3) {} 'byte array for length
Dim Buffer As Byte() 'byte array for msg
OutputData = Newtonsoft.Json.JsonConvert.SerializeObject(ResponseData) 'convert the array to JSON
Buffer = System.Text.Encoding.UTF8.GetBytes(OutputData) 'convert the response to byte array
LenBytes = System.BitConverter.GetBytes(Buffer.Length) 'convert the length of response to byte array
Using StdOut As System.IO.Stream = Console.OpenStandardOutput() 'Using for easy disposal
StdOut.WriteByte(LenBytes(0)) 'send the length 1 byte at a time
StdOut.WriteByte(LenBytes(1))
StdOut.WriteByte(LenBytes(2))
StdOut.WriteByte(LenBytes(3))
For i As Integer = 0 To Buffer.Length - 1 'loop the response out byte at a time
StdOut.WriteByte(Buffer(i))
Next
End Using
End Sub
End Module
From the Chrome Extension, open a connection, send a message, and once a response is received the host will close. Check our Chrome's Dev page for a sample app/extension: https://developer.chrome.com/apps/nativeMessaging
I hope this helps somebody, and please let me know if you make any improvements!
Sub Main() ' Recursive Version
Try
Dim stdin As Stream = Console.OpenStandardInput()
Dim stdout As Stream = Console.OpenStandardOutput()
Dim MsgLength As Integer = 0
Dim InputData As String = ""
Dim LenBytes As Byte() = New Byte(3) {}
stdin.Read(LenBytes, 0, 4)
MsgLength = BitConverter.ToInt32(LenBytes, 0)
Dim Buffer As Byte() = New Byte(MsgLength - 1) {}
stdin.Read(Buffer, 0, Buffer.Length)
InputData = Encoding.UTF8.GetString(Buffer)
Dim Str As String = Newtonsoft.Json.JsonConvert.SerializeObject("[" & Now & "] Arrrr!")
Dim buff() As Byte = Encoding.UTF8.GetBytes(Str)
stdout.Write(BitConverter.GetBytes(buff.Length), 0, 4)
stdout.Write(buff, 0, buff.Length)
Main()
Catch ex As Exception
MsgBox(ex.Message, MsgBoxStyle.Critical, "Oh, Snap!")
End Try
End Sub

My program "stuck in this line" reading stream

This
So I am reading a stream like usual. Then it just stuck. It doesn't throw exception or anything. It just stucks.
Try
Do
read = stream.Read(datain, 0, datain.Length) 'Stuck here
responseData = System.Text.Encoding.ASCII.GetString(datain, 0, read)
finalResponse = finalResponse + responseData
Loop While read > 0
Catch ex As Exception
What should I do so that the program would never get stuck like that? Notice I already put the code inside try catch block
Here is the full program.
Public Function getWhoisInfoAsText4(strDomainName As String, whoisServerToTry As String) As String
'testAsisWhois()
Dim data = System.Text.Encoding.ASCII.GetBytes(strDomainName & Microsoft.VisualBasic.vbCr & Microsoft.VisualBasic.vbLf)
Dim finalResponse = String.Empty
Dim client As TcpClient
Try
client = New TcpClient(whoisServerToTry, 43)
Catch ex As Exception
Return ""
End Try
Dim stream = client.GetStream()
Using stream
stream.Write(data, 0, data.Length)
Dim datain = New Byte(254) {}
Dim responseData = String.Empty
Dim read As Integer
Try
Do
read = stream.Read(datain, 0, datain.Length)
responseData = System.Text.Encoding.ASCII.GetString(datain, 0, read)
finalResponse = finalResponse + responseData
Loop While read > 0
Catch ex As Exception
End Try
End Using
If finalResponse.Contains("Name Server:") Then
appendToTextFile(whoisServerToTry + vbNewLine, "appendfiles", Scripting.IOMode.ForAppending)
End If
finalResponse += (whoisServerUsed + whoisServerToTry + vbNewLine)
Return finalResponse
End Function
does your program stuck at the first loop sequence?
According to MSDN mabye this should help
Dim numBytesRead as Integer = 0
Do
read = stream.Read(datain, numBytesRead, datain.Length)
responseData = System.Text.Encoding.ASCII.GetString(datain, 0, read)
finalResponse = finalResponse + responseData
numBytesRead += read
Loop While read > 0
Stream.Read waits always until the amount of bytes it is expecting is coming, if there is an interruption on the communication just in the moment the program is exactly on the Read and the connection get close the program will be forever in this point waiting for the rest of the bytes to come unless you will configure a ReadTimeout, then after not receiving any bytes during this time it will throw an exception.
You should then make a try catch and restart the connection.