TCP Socket doesn't send all the data - vb.net

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

Related

Can I send data using the same TCP port?

I have a TCP listener working but doesn't send anything. To get this TCP listener working I have a thread in a endless loop.
Now I need to answer to some specific packets and also be able to send data when the user request it using the same port that the TCP listener is using. The remote device keeps the connection open to be able to receive new data.
So, I must to create a new TCP client to send data to the current connected client or use the current listener socket?
Public Sub StopServer()
TcpOpen = False
Server.Stop()
ServerThread = Nothing
End Sub
Public Sub InitServer(ByVal Port As Integer)
Server = New TcpListener(IPAddress.Any, Port)
ServerThread = New Thread(AddressOf ConnectionListener)
ServerThread.IsBackground = True
ServerThread.Start()
TcpOpen = True
End Sub
Private Sub ConnectionListener()
Server.Start()
While True
If TcpOpen Then
If Server.Pending Then
Dim client As TcpClient = Server.AcceptTcpClient()
Dim T As New Thread(AddressOf StartTcpClient)
client.ReceiveBufferSize = 128000
T.IsBackground = True
T.Start(client)
Else
System.Threading.Thread.Sleep(10)
End If
Else
Exit While
End If
End While
End Sub
Private Sub StartTcpClient(ByVal client As TcpClient)
Dim bytesRead As Integer
Dim RxBuffer(1500) As Byte 'Original 1024
Dim RxDataStr As String = ""
Dim TxBuffer(1500) As Byte
Dim TxDataStr As String = ""
Dim TempData As String
Dim DataReceived As Boolean = False
Dim TimeX As Integer = 0
Dim RemoteIP As Net.IPEndPoint = client.Client.RemoteEndPoint
Dim RemoteIPStr As String = RemoteIP.Address.ToString
WriteRTBLog("Se inicio una nueva conexion TCP con la IP " & RemoteIPStr, Color.DarkViolet)
WriteRTBLog("Esperando datos...", Color.Black)
client.ReceiveTimeout = 30000
Try
While True
If client.GetStream.DataAvailable Then
bytesRead = client.GetStream.Read(RxBuffer, 0, RxBuffer.Length)
TimeX = 0 'Reset timer
If bytesRead > 0 Then
TempData = System.Text.ASCIIEncoding.UTF8.GetString(RxBuffer, 0, bytesRead) 'UTF8
RxDataStr += TempData
If Not DataReceived Then
DataReceived = True
WriteRTBLog("Se estan recibiendo datos...", Color.Purple)
End If
If RxDataStr.Contains("<") Then
'Process data
TxDataStr = AnswerProcessor(RxDataStr)
'New code- trying to send data
If TxDataStr.Length > 5 Then
TxBuffer = System.Text.Encoding.ASCII.GetBytes(TxDataStr)
client.Client.Send(TxBuffer)
End If
RxDataStr = "" 'Clean buffer
End If
End If
Else
If Not client.Connected Then
Exit While 'Close connection
Else
System.Threading.Thread.Sleep(10)
End If
End If
End While
If RxDataStr.Length > 0 Then
WriteRTBLog(String.Format("Se recibieron {0} bytes desde {1}", RxDataStr.Length.ToString, RemoteIPStr), Color.ForestGreen)
If Not client.Connected Then
WriteRTBLog("Conexion cerrada", Color.Black)
End If
End If
Catch ex As Exception
client.Close()
WriteRTBLog("Error en la conexion a " & RemoteIPStr, Color.Red)
WriteRTBLog(ex.Message, Color.Red)
WriteRTBLog(ex.StackTrace, Color.Red)
If RxDataStr.Length > 0 Then
' Create the file.
Dim PathX As String = Application.StartupPath & "\TCP_File_err" & CLng(DateTime.UtcNow.Subtract(New DateTime(1970, 1, 1)).TotalMilliseconds) & ".TCP"
Using fs As FileStream = File.Create(PathX)
Dim data As Byte() = New ASCIIEncoding().GetBytes(RxDataStr)
' Add some information to the file.
fs.Write(data, 0, data.Length)
End Using
WriteRTBLog(String.Format("Se recibieron {0} bytes desde {1} y se guardaron en {2}.", RxDataStr.Length.ToString, RemoteIPStr, PathX), Color.ForestGreen)
End If
End Try
End Sub
So, I must to create a new TCP client to send data to the current connected client or use the current listener socket?
No, neither. Use the socket you accepted that's connected to the client.

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.

Hostednetwork show login page

I'm currently writing a program that opens a wifi hotspot and enables Internet Connection sharing. I've got all of this working with netsh wlan set hostednetwork and some WinAPI calls.
Now I'd like to be able to show a login page when a client connects or block some websites/ports/etc.
My idea on this was to monitor the connection between me (the access point) and the client and whenever a packet on port 80 occurs, I send my login page or a "website blocked" page back instead of the real page. Currently the program is able to monitor the connection but I don't know how to send it back to the client.
This is my code (it's a bit long):
Dim myIpaddress As IPAddress
Dim theSocket As Socket
Dim receiveBuffer(4096) As Byte
Dim content As String = ""
Dim protocol As String = ""
Dim ipFrom As IPAddress
Dim ipTo As IPAddress
Dim portFrom As UInteger
Dim portTo As UInteger
Sub Listen()
theSocket = New Socket(AddressFamily.InterNetwork, SocketType.Raw, ProtocolType.IP)
For Each int As NetworkInterface In NetworkInterface.GetAllNetworkInterfaces
If int.Description.Contains("Hosted") Then
For Each adress As UnicastIPAddressInformation In int.GetIPProperties.UnicastAddresses
If adress.Address.AddressFamily = AddressFamily.InterNetwork Then
myIpaddress = adress.Address
BindSocket()
End If
Next
End If
Next
End Sub
Sub BindSocket()
Try
theSocket.Bind(New IPEndPoint(myIpaddress, 0))
theSocket.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.HeaderIncluded, True)
theSocket.IOControl(IOControlCode.ReceiveAll, {1, 0, 0, 0}, {1, 0, 0, 0})
receiveBuffer = New Byte(theSocket.ReceiveBufferSize) {}
theSocket.BeginReceive(receiveBuffer, 0, receiveBuffer.Length, SocketFlags.None, New AsyncCallback(AddressOf OnReceive), Nothing)
Catch ex As Exception
End Try
End Sub
Private Sub OnReceive(ByVal asyncresult As IAsyncResult)
'Get Length of packet (including header)
Dim readlength As UInteger = BitConverter.ToUInt16(Byteswap(receiveBuffer, 2), 0)
portTo = BitConverter.ToUInt16(Byteswap(receiveBuffer, 22), 0)
portFrom = BitConverter.ToUInt16(Byteswap(receiveBuffer, 24), 0)
'Get Protocol Type
If receiveBuffer(9) = 6 Then
protocol = "TCP"
ElseIf receiveBuffer(9) = 17 Then
protocol = "UDP"
Else
protocol = "???"
End If
'Get IP from and to
ipFrom = New IPAddress(BitConverter.ToUInt32(receiveBuffer, 12))
ipTo = New IPAddress(BitConverter.ToUInt32(receiveBuffer, 16))
content = ""
For i = 26 To readlength - 1
If Char.IsLetterOrDigit(Chr(receiveBuffer(i))) = True Then
content = content & Chr(receiveBuffer(i))
Else
content = content & "."
End If
Next
'TODO how to send my content to the client?
'Restart the Receiving
theSocket.BeginReceive(receiveBuffer, 0, receiveBuffer.Length, SocketFlags.None, New AsyncCallback(AddressOf OnReceive), Nothing)
End Sub
Private Function Byteswap(ByVal bytez() As Byte, ByVal index As UInteger)
Dim result(1) As Byte
result(0) = bytez(index + 1)
result(1) = bytez(index)
Return result
End Function
Any ideas?

There's a way know when a TCP payload ends?

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

VB .net : How can a Server handle multiple clients simultaneosly at an instance

I am facing a problem in VB .net Client/Server application where I am successfully able to talk between them using TCPListener and TCPClient class usage. However, when I try to connect another Client to the same server on the same welcome port, it errors out throwing an exception or behaves very unexpectedly.
Isn't it true that the Server connection is on a WELCOME PORT for all the clients, and that each client connected gets a new port to carry on its communication with the server AUTOMATICALLY (according to the Tomcat webserver working)?
OR, is the above statement untrue and that the APP program handle the connections manually?
Pls clarify with an example in VB .net, if possible?
The answer to your question is 'Yes it is true'. I do not have VB.NET code ready but you can have a look at C# code here C# sockets handling multiple clients.
Okay.. pasting my server code here for your comments... Pls pardon my ignorance in coding and teach me if I were wrong. Thanks.
The Client is more obvious... so dint paste it here.
Server:
Public Class ServerSide2
...other stuff...
Public Class Packet
Public packetType As String = "Data"
Public packetOwnerIPAddress As String
Public packetOwnerPort As String
Public content As String
Public Sub New(ByVal type As String, ByVal ip As String, ByVal port As String, ByVal data As String)
packetType = type
packetOwnerIPAddress = ip
packetOwnerPort = port
content = data
End Sub
End Class
Public Class Worker
Dim myLogger As Logger
Dim name As String
Dim ipClientAddress As IPAddress 'Client's IP address
Dim ipClientPort As Integer = 22222 'Client listening on this port
Dim tcpServer As TcpListener
Dim tcpClient As TcpClient
Dim networkStream As NetworkStream
Dim readSize As Integer = 100
Public Sub New(ByRef logger As Logger, ByVal id As String)
myLogger = logger
name = id
myLogger.Trace("A new Worker object has been created for client: {0}", ipClientAddress)
End Sub
'Listener code
Public Sub runClientHandler(ByVal ar As IAsyncResult)
'code to listen to independent client
Dim clientdata As String
Dim numBytesRead As Integer = 0
Thread.CurrentThread.Priority = ThreadPriority.Highest
' Get the listener that handles the client request.
Dim listener As TcpListener = CType(ar.AsyncState, TcpListener)
' End the operation and display the received data on
' the console.
tcpClient = listener.EndAcceptTcpClient(ar)
' Process the connection here. (Add the client to a
' server table, read data, etc.)
myLogger.Info("Client connected completed")
' Signal the calling thread to continue.
tcpClientConnected.Set()
networkStream = tcpClient.GetStream()
Dim ipEndPoint As IPEndPoint = tcpClient.Client.RemoteEndPoint
ipClientAddress = ipEndPoint.Address
myLogger.Info("A new Worker thread has been started.")
While Not stopping
myLogger.Trace("Start looping.")
Dim bytes(readSize) As Byte
numBytesRead = networkStream.Read(bytes, 0, bytes.Length)
clientdata = Encoding.ASCII.GetString(bytes, 0, numBytesRead)
'check for validity of the data
If numBytesRead = 0 Then
'connection lost
myLogger.Trace("No data read.")
Exit While
End If
If clientdata.Contains("SampleTest : {") Then
'Message box the client data
MsgBox("Test data from Client = " + clientdata)
myLogger.Trace("Test data from Client = " + clientdata)
ElseIf clientdata.Contains("Recieve Port : ") Then
'Heed to Client's request on the port number server should reply
Dim dest(5) As Char
Dim destString As String = ""
clientdata.CopyTo(15, dest, 0, clientdata.Length - 15)
ipClientPort = CInt(CStr(dest))
myLogger.Trace("Client Waiting on Port# : " + CStr(dest) + "for sorted packets.")
'MsgBox("Client Waiting on Port# : " + CStr(dest))
ElseIf clientdata.Contains("Packet Size : ") Then
Dim dest(5) As Char
Dim destString As String = ""
clientdata.CopyTo(14, dest, 0, clientdata.Length - 14)
readSize = CInt(CStr(dest))
myLogger.Trace("Client's communicated Packet Size : " + CStr(dest))
Else
myLogger.Info("Begin to queue Data Packets.")
While True
myLogger.Info("Data Packet.")
SyncLock Stats.locker
myLogger.Info("Got the lock.")
Stats.queueLength = Stats.requestQueue.Count
If Stats.queueLength < Stats.MAX_QUEUE_LENGTH Then
'Queue has some space to fit more packets
myLogger.Info("Queue has some space for this packet.")
Stats.packetNum = Stats.packetNum + 1
Dim newPacket As Packet = New Packet("Data", ipClientAddress.ToString, ipClientPort, clientdata)
Stats.requestQueue.Enqueue(newPacket)
Stats.sumQueueLength = Stats.sumQueueLength + Stats.requestQueue.Count
Stats.meanQueueLength = Stats.sumQueueLength / Stats.packetNum
myLogger.Info("Stats :: Packet #: {0}, QueueLength: {1}, MeanQueueLength: {2}.", Stats.packetNum, Stats.requestQueue.Count, Stats.meanQueueLength)
Else
'Queue is FULL, Ignore the packet
Stats.numDropPackets = Stats.numDropPackets + 1
myLogger.Info("Stats :: Dropped Packets: {0}.", Stats.numDropPackets)
End If
End SyncLock
numBytesRead = networkStream.Read(bytes, 0, bytes.Length)
clientdata = Encoding.ASCII.GetString(bytes, 0, numBytesRead)
'check for validity of the data
If numBytesRead = 0 Then
'connection lost
myLogger.Trace("No data read.")
Exit Sub
End If
End While
End If
End While
myLogger.Trace("End looping.")
End Sub
End Class
Sub ListeningThread()
Dim count As Integer = 0
tcpServer = New TcpListener(ipAddress, iPort)
tcpServer.Start()
Try
While Not stopping And count < Stats.MAX_CLIENTS
count = count + 1
Dim workerName = "worker:" + CStr(count)
Dim worker As Worker = New Worker(logger, workerName)
logger.Info("Waiting for a client to connect")
DoBeginAcceptTcpClient(worker, tcpServer)
logger.Info("Connected to {0}.", workerName)
'Add the client to the hashTable
'ADITYA later clients.Add(workerName, client)
If SortAndSendThrd Is Nothing Then
'Start a new thread
SortAndSendThrd = New Thread(SortAndSendThrdStart)
SortAndSendThrd.Priority = ThreadPriority.Highest
End If
If Not SortAndSendThrd.IsAlive Then
SortAndSendThrd.Start()
logger.Debug("Started off a Sort thread")
End If
'Dim i As Integer = 0
'Dim objValue As Object
'For Each objKey In clients.Keys
' objValue = clients.Item(objKey)
' 'MsgBox("[" & objKey.ToString & ", " & objValue.ToString & "]")
'Next objKey
End While
Catch ex As IOException
ToolStripStatusLabel1.Text = "ERROR : SocketException: {0}" + ex.Message
'MsgBox(ex.Message + ":::2")
Catch ex As SocketException
ToolStripStatusLabel1.Text = "ERROR : SocketException: {0}" + ex.Message
'MsgBox(ex.Message + ":::1")
End Try
'tcpServer.Stop()
'client.Close()
logger.Debug("The Server's listening handler has come to an end.")
End Sub
End Class
When I try to connect a second client to this, the server drops the connection 1 and behaves unpredictably.