Can I send data using the same TCP port? - vb.net-2010

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.

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

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?

What I must change to make this code listen on UDP port?

I'm trying to create a server Windows Form application but my code throw a 0x80004005 error when call the Listen method.
What I'm doing wrong?
Private Sub StartUdpReceiveThread(ByVal Puerto As Integer)
If Not UdpOpen Then
Try
permission = New SocketPermission(NetworkAccess.Accept, TransportType.Udp, "", SocketPermission.AllPorts)
sListener = Nothing
permission.Demand()
'Dim ipHost As IPHostEntry = Dns.GetHostEntry("")
Dim ipAddr As IPAddress = IPAddress.Any
ipEndPoint = New IPEndPoint(ipAddr, CInt(Me.PuertoEscuchaLbl.Text))
'sListener = New Socket(ipAddr.AddressFamily, SocketType.Unknown, ProtocolType.Udp)
sListener = New Socket(ipAddr.AddressFamily, SocketType.Dgram, ProtocolType.UDP)
' Associates a Socket with a local endpoint
sListener.Bind(ipEndPoint)
sListener.Listen(5)
' Begins an asynchronous operation to accept an attempt
Dim aCallback As New AsyncCallback(AddressOf AcceptCallback)
sListener.BeginAccept(aCallback, sListener)
PrintLog("Server listening on " & ipEndPoint.Address.ToString & " port: " & ipEndPoint.Port)
UdpOpen = True
Catch ex As Exception
MessageBox.Show(ex.ToString())
End Try
End If
End Sub
Edit:
CallBack method
Public Sub AcceptCallback(ar As IAsyncResult)
Dim listener As Socket = Nothing
' A new Socket to handle remote host communication
Dim handler As Socket = Nothing
Try
' Receiving byte array
Dim buffer As Byte() = New Byte(1023) {}
' Get Listening Socket object
listener = DirectCast(ar.AsyncState, Socket)'<-- Here raises an error
' Create a new socket
handler = listener.EndAccept(ar)
handler.NoDelay = False
' Creates one object array for passing data
Dim obj As Object() = New Object(1) {}
obj(0) = buffer
obj(1) = handler
handler.BeginReceive(buffer, 0, buffer.Length, SocketFlags.None, New AsyncCallback(AddressOf ReceiveCallback), obj)
' Begins an asynchronous operation to accept an attempt
Dim aCallback As New AsyncCallback(AddressOf AcceptCallback)
listener.BeginAccept(aCallback, listener)
Catch ex As Exception
MessageBox.Show(ex.ToString())
End Try
End Sub
Don't just pick the first IP address in IPHostEntry.AddressList but search the array for an IPv4 address. See the example on this MSDN page.

VB.NET TCP Server Receiving Data Properly

I have a multithread(with Backgroundworker) TCP Server which is developed by VB.NET. It works very good when client and server at same machine. But when i connect to server from another computer which is at same LAN it works different. At this case it works good until i start to send messages consecutively (3-4 messages at a second). I send :
Hi
Hi
Hi
Hi
Hi
and server gets this messages such :
Hi
HiHi
HiHiHi
Hi
etc.
It's very interesting that this issue occurs only when client is at other computer at LAN.
Here is my listen Sub :
Sub listen_port6(ByVal b As BackgroundWorker)
Dim server As TcpListener
server = Nothing
Try
Dim port As Int32 = 8085
server = New TcpListener(IP, port)
server.Start()
Dim bytes(1024) As Byte
Dim data As String = Nothing
While True
Dim client As Sockets.TcpClient = server.AcceptTcpClient()
Dim ipend As Net.IPEndPoint = client.Client.RemoteEndPoint
PublicIP = ""
If Not ipend Is Nothing Then
PublicIP = ipend.Address.ToString
End If
b.ReportProgress(1)
Dim stream As NetworkStream = client.GetStream()
Dim i As Int32
Dim k As Short
For k = 0 To 1024
bytes(k) = 0
Next
i = stream.Read(bytes, 0, bytes.Length)
While (i <> 0)
data = ""
data = System.Text.Encoding.ASCII.GetString(bytes, 0, i)
Debug.Print(data)
i = stream.Read(bytes, 0, bytes.Length)
End While
client.Close()
End While
Catch errore As Exception
Error_Print(errore.Message)
Finally
server.Stop()
End Try
End Sub
Thanks in advance

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.