This is the code I have a problem on.
In my form load, I got this:
Dim port as new Ports.SerialPort("MyPort", 100000)
port.DataBits = 8
port.StopBits = Ports.StopBits.One
port.Parity = Ports.Parity.None
port.Open()
System.Threading.Thread.Sleep(200)
Then in my button1.Click event, I got this:
Try
If port.IsOpen Then
Dim inStream(80) As Byte
port.Read(inStream, 0, 80)
Dim returndata As String = System.Text.Encoding.ASCII.GetString(inStream, 0, 80)
returndata = returndata.Replace(Chr(2), "A")
returndata = returndata.Replace(Chr(3), "B")
msg("Data from Server : " + returndata)
Dim data As String
data = Write(TextBox2.Text, TextBox2.Text.Substring(0, 4))
Dim outStream As Byte() = _
System.Text.Encoding.ASCII.GetBytes(STX & data & ETX) '("Message from Client$")
ashsp.Write(outStream, 0, outStream.Length)
End If
Catch ex As Exception
End try
The problem here now is when I click button1, I got a TimeoutException when it hits port.Read(inStream, 0, 80).
Are you sure there are exactly 80 bytes to read? You could use the BytesToRead property to dynamically check how many bytes are available. Or if you are receiving only text on the serial port you could use the ReadExisting() method which puts all available bytes into a string object.
Related
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
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.
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?
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.
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.