Visual Basic Com Port doesn't Receive - vb.net

I'm Trying to communicate with a com port using a visual basic console application. The com port never receives data, and times out every time. I've confirmed with a different program written in python that the com port and device are working correctly. I am sure that I am just missing something since I am new to VB. I've tried opening the com port using two method, neither of which returned an error (the first method I used is commented out). Below is my script.
Imports System
Imports System.IO.Ports
Imports System.IO
Module Module1
Function ReceiveSerialData(ByVal data As String) As String
' Receive strings from a serial port.
Dim returnStr As String = ""
Dim add As String = "Com6"
'Dim port As New SerialPort("Com6", 9600, Parity.None, 8, StopBits.One)
Dim port As SerialPort = My.Computer.Ports.OpenSerialPort("COM6", 9600, Parity.None, 8, StopBits.One)
Try
Dim state As Boolean = (port.IsOpen)
If state = False Then
Console.Write("Opening Port" + vbNewLine)
port.Open()
End If
port.ReadTimeout = 5000
port.Write("z")
Dim cat As String = port.ReadLine()
Catch ex As TimeoutException
returnStr = "Error: Serial Port read timed out."
Finally
If port IsNot Nothing Then port.Close()
End Try
Console.Write(returnStr)
Return returnStr
End Function
Sub Main()
Console.WriteLine("Enter Command for Telescope!:")
Dim stdin As TextReader = Console.In
Dim sInput As String = stdin.ReadLine
Console.Write("Sending Command " + sInput + "." + vbNewLine)
Dim sent As String
sent = "z"
Dim recv As String
recv = ReceiveSerialData(sent)
Console.Write(recv)
End Sub
End Module

Related

TCP Client program won't connect to my server

I'm trying to create a basic chat server-client program using TCP/IP and port forwarding in VB.NET. The code is derived almost entirely from Carlo De Silva's YouTube tutorials. I'm consistently having an issue connecting the two clients. When I open the client on my computer and another client on the other computer, I get the error "A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond [ip]:5757"
There are three different programs: the server, the client, and the client on the other end (the friend client.) The server and the client both use my local IP, which is accessed programmatically, so it couldn't be due to a typo. The friend client uses my external IP, which I've checked as of today (2018-09-09) and it is correct. I've set up port-forwarding on my router using TCP&UDP with my local IP, which was different when I checked it today, but I've updated the rule and the problem persists. Everything is done over port 5757. The firewall isn't an issue - I tried turning it off on the other computer and the friend client still fails to connect.
I've checked the port-forwarding tester on the website yougetsignal.com, which says that port 5757 is closed on both my local and external IP. But at the time of writing, I've currently got open the server and two client programs (both of which use my local IP,) and I am able to successfully send messages between those two client programs. So if they are able to send messages between the server and back, I don't understand why the website says that the port is closed on my local IP.
Can anyone help me work out why the friend client is failing to connect?
Server code:
Module MainModule
Dim _server As TcpListener
Dim _listOfClients As New List(Of TcpClient)
Dim hostName As String = System.Net.Dns.GetHostName
Dim ip As String = System.Net.Dns.GetHostEntry(hostName).AddressList(0).ToString
Dim extip As String = "86.25.175.94"
Dim port As Integer = 5757
Sub Main()
Console.Title = "SERVER"
Try
_server = New TcpListener(IPAddress.Parse(ip), port)
_server.Start()
Threading.ThreadPool.QueueUserWorkItem(AddressOf NewClient)
Catch ex As Exception
Console.WriteLine(ex.Message)
End Try
Console.ReadLine()
End Sub
Private Sub NewClient(state As Object)
Dim client As TcpClient = _server.AcceptTcpClient
Try
Threading.ThreadPool.QueueUserWorkItem(AddressOf NewClient)
_listOfClients.Add(client)
Dim ns As NetworkStream = client.GetStream
While True
'Creates a buffer
Dim toReceive(100000) As Byte
Dim length As Integer = ns.Read(toReceive, 0, toReceive.Length)
Dim text As String = Encoding.ASCII.GetString(toReceive, 0, length)
For Each c As TcpClient In _listOfClients
If c IsNot client Then 'Sends a message to every other client besides this one.
Dim nns As NetworkStream = c.GetStream 'New Network Stream
nns.Write(Encoding.ASCII.GetBytes(text), 0, text.Length)
End If
Next
Console.WriteLine(text)
Console.WriteLine()
'Sends a received message receipt.
Dim toSend() As Byte = Encoding.ASCII.GetBytes("Message Received...")
ns.Write(toSend, 0, toSend.Length)
End While
Catch ex As Exception
If _listOfClients.Contains(client) Then
_listOfClients.Remove(client)
End If
Console.WriteLine(ex.Message)
End Try
End Sub
End Module
Client code:
Module MainModule
Dim _client As TcpClient
Dim hostName As String = System.Net.Dns.GetHostName
Dim ip As String = System.Net.Dns.GetHostEntry(hostName).AddressList(0).ToString
Dim extip As String = "86.25.175.94"
Dim port As Integer = 5757
Sub Main()
Console.Title = "Chat Client (Host)"
Try
'Gets the local ip address
_client = New TcpClient(ip, port)
'This thread listens for receiving messages from the server.
Threading.ThreadPool.QueueUserWorkItem(AddressOf ReceiveMessages)
While True
'Starts a new stream
Dim ns As NetworkStream = _client.GetStream()
Dim message As String = Console.ReadLine()
Dim toSend() As Byte = Encoding.ASCII.GetBytes(message)
'Sends the message to the server
ns.Write(toSend, 0, toSend.Length)
End While
Catch ex As Exception
Console.WriteLine(ex.Message)
End Try
Console.ReadLine()
End Sub
Private Sub ReceiveMessages(state As Object)
Try
While True
'Starts a new network stream (receiving stream) to listen for any receiving messages.
Dim rs As NetworkStream = _client.GetStream
'Creates a buffer to receive text
Dim toReceive(100000) As Byte
'Reads anything coming in from the server.
Dim length As Integer = rs.Read(toReceive, 0, toReceive.Length)
'Converts the byte to text
Dim text As String = Encoding.ASCII.GetString(toReceive, 0, length)
Console.ForegroundColor = ConsoleColor.Green
Console.WriteLine(text)
Console.ResetColor()
Console.WriteLine()
End While
Catch ex As Exception
Console.WriteLine(ex.Message)
End Try
End Sub
End Module
The client and friend client are only different by one line of code:
_client = New TcpClient(extip, port) 'Friend client connects to external IP
_client = New TcpClient(ip, port) 'My client connects to local IP
Your issue is here:
_server = New TcpListener(IPAddress.Parse(ip), port)
The TcpListener(IPAddress, Int32) overload specifies which IP address to accept connections from, meaning it will accept connections from ONLY that IP (in this case your local address).
To fix this you've got to listen for connections at IPAddress.Any (equivalent to 0.0.0.0), which specifies that it should accept connections from any IP address.
_server = New TcpListener(IPAddress.Any, port)

VB.net TCP Non-Blocking State

I have code that sending string from client to server with TCP Connection.
But i dont know how to convert it to NonBlocking TCP State Connection.
i have try to put socket.Blocking = FALSE, but that code give me an error.
Socket Error Code: 10035
Exception Title: A non-blocking socket operation could not be completed immediately
Heres my code for sending string from client to server.
Server Code :
Imports System.Net
Imports System.Net.Sockets
Imports System.Text
Module Module1
Dim soket As Socket
Sub Main()
Try
Dim alamatIP As IPAddress = IPAddress.Parse("127.0.0.1")
Dim tcpListener As New TcpListener(alamatIP, 8000)
'soket.Blocking = False - THIS WILL GIVE ME AN ERROR
tcpListener.Start()
System.Console.WriteLine("Server port 8000...")
Dim myendpoint As IPEndPoint
myendpoint = CType(tcpListener.LocalEndpoint, IPEndPoint)
System.Console.WriteLine("IP : " + myendpoint.Address.ToString + " and port is " + myendpoint.Port.ToString)
System.Console.WriteLine("Waiting for connection !")
soket = tcpListener.AcceptSocket()
myendpoint = CType(soket.RemoteEndPoint(), IPEndPoint)
System.Console.WriteLine("Receiving from " + myendpoint.Address.ToString())
Dim bitData(100) As Byte
Dim newString As String = ""
Do
Try
Dim size As Integer = soket.Receive(bitData)
newString = Encoding.ASCII.GetString(bitData)
Console.WriteLine(newString)
Array.Clear(bitData, 0, bitData.Length)
Catch ex As Exception
Console.Write(ex.ToString())
End Try
Loop While newString <> "exit"
soket.Close()
tcpListener.Stop()
Catch ex As Exception
Console.WriteLine("Error ..." + ex.ToString())
End Try
Console.ReadLine()
End Sub
End Module
Client Code :
Imports System.Net
Imports System.Net.Sockets
Imports System.Text
Imports System.IO
Imports System.Threading
Module Module1
Sub Main()
Try
Dim tcpClient As New TcpClient 'creating the client
Console.WriteLine("Connecting....")
tcpClient.Connect("127.0.0.1", 8000) 'connecting the client the server
'port is same as in the server
Console.WriteLine("Connected")
Console.WriteLine("Enter the string to be transmitted : ")
Dim strMessage As String
Dim stm As Stream
Dim counter As Integer = 0
Do
stm = tcpClient.GetStream() 'getting the stream of the client
Dim ascenc As New ASCIIEncoding
strMessage = Console.ReadLine()
Dim byteData() As Byte = ascenc.GetBytes(strMessage)
Console.WriteLine("Transmitted ")
stm.Write(byteData, 0, byteData.Length())
Loop While strMessage <> "exit"
tcpClient.Close() 'closing the connection
Catch ex As Exception
Console.WriteLine("Error..." + ex.StackTrace.ToString()) 'writing the exception into the console
End Try
End Sub
End Module
Thanks for any help.
When you attempt to read from a non-blocking socket or write to it and the operation cannot be completed right now, then the socket is supposed to signal an error. In VB it means it is supposed to raise an exception. For example, this happens when your machine hasn't received any data but you try to Read something.
Before trying an operation on a non-blocking socket, call Select or Poll in order to make sure it is ready for the operation.

Receive many file with server

I use a program to receive file that client send with specific port.
The problem is when a lot of client send file to this server, it wait to receive file in order, it receive files consecutive.
Now i need help to change this code that it received files Parallel.
For example 10 client, send file to this server.it receive all file in order, but i need it receive them Parallel.
I hope you understand what i want.
Imports System.Net
Imports System.Net.Sockets
Imports System.Threading
Imports System.IO
Module Module1
Public destinationfolder As String
Dim rcf As New RecievedFile
Public port As String
Sub Main()
Console.Title = "B64S Server"
Console.WindowHeight = 30
DrawGraphics(2)
Console.ForegroundColor = ConsoleColor.Gray
Console.WriteLine(" Created by: Turbocharged Chameleon")
DrawGraphics(2) ''draws some graphics from another sub
DrawGraphics(0)
DrawGraphics(2)
Console.ForegroundColor = ConsoleColor.White
Console.WriteLine("Destination Folder:")
destinationfolder = Console.ReadLine() ''reads line for destination folder
Console.WriteLine("Port:")
port = Console.ReadLine() ''reads line and sets the port
If Directory.Exists(destinationfolder) = False Then
MsgBox("destination folder doesn't exist!")
End ''ends program if folder doesn't exist
End If
Console.Clear()
''wait
DrawGraphics(1)
rcf.Threader = New Thread(New System.Threading.ThreadStart(AddressOf rcf.enter code hereRecieve))
rcf.Threader.Start() ''starts listening on port for incoming data
End Sub
Private Sub DrawGraphics(ByVal int As Integer)
If int = 0 Then
Console.ForegroundColor = ConsoleColor.Gray
Console.WriteLine("MMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM")
Console.WriteLine("MMMMMMMMMMMMMM$,.........$MMMMOMMMMMMMMM")
Console.WriteLine("MMMMMMMMMMM8,,......... .. M....MMMMMMM")
ElseIf int = 1 Then
Console.ForegroundColor = ConsoleColor.Gray
Console.WriteLine("MMMMMMMMMMMMMMMII+++:::::==+++??$$$MMMMM")
Console.WriteLine("MMMMMMMMMMII???~~.............~~$$$MMMMM")
Console.WriteLine("MMMMMMMMMMII???~~.............~~$$$MMMMM")
ElseIf int = 2 Then
Console.ForegroundColor = ConsoleColor.Red
Console.WriteLine("----------------------------------------")
End If
End Sub
End Module
and Recieved File Class:
Public Class RecievedFile
Public Threader As Thread
Dim TCPListener As TcpListener
Dim Socket As Socket
Sub Recieve()
Try
TCPListener = New TcpListener(IPAddress.Any, port)
TCPListener.Start()
While True
Try
Socket = TCPListener.AcceptSocket
Dim MyNetworkStream As NetworkStream = New NetworkStream(Socket)
Dim mystreamreader As StreamReader = New StreamReader(MyNetworkStream)
Console.WriteLine("Recieving file...")
Dim str As String = mystreamreader.ReadToEnd
Console.WriteLine(str)
Dim fn As String = str.Remove(str.IndexOf("#"))
Dim filenamelength As Integer = fn.Length
Dim b64string As String = str.Substring(str.IndexOf("#") + 1)
Console.WriteLine("BS64")
Dim binaryData() As Byte = Convert.FromBase64String(b64string)
Console.WriteLine("done")
If My.Computer.FileSystem.FileExists(destinationfolder & "\" & fn) Then
System.IO.File.Delete(destinationfolder & "\" & fn)
Dim fs As New FileStream(destinationfolder & "\" & fn, FileMode.CreateNew)
fs.Write(binaryData, 0, binaryData.Length)
fs.Close()
Console.WriteLine("Recieved file: " & fn)
Else
Dim fs As New FileStream(destinationfolder & "\" & fn, FileMode.CreateNew)
fs.Write(binaryData, 0, binaryData.Length)
fs.Close()
Console.WriteLine("Recieved file: " & fn)
End If
Catch ex As Exception
MsgBox(ex.Message)
End Try
End While
Catch ex2 As Exception
MsgBox(ex2.Message)
End Try
End Sub
End Class
Maybe pass the receiver part of the code into a new instance of a background worker?
That might allow each stream to come in on its own thread.
I haven't tried, but that was just the first thought that came to mind.

Socket program freezes on load

The program freezes on load. At first it was working as it was supposed to, but after I cleaned and built the solution, it only freezes on load. The weird part is that it only freezes and it does not show the exception message for the catch.
here is the class file I used
Imports System.Net ' for IPAddress
Imports System.Net.Sockets 'for TcpListener
Public Class clientSocket
Dim aString As String
Dim port As Integer 'this is the port number
Dim localAddr As IPAddress ' this is the IP address
Dim client As TcpClient ' This is for the TCP/IP Protocol
Dim clientListener As TcpListener
Public Function startSocket() As String
Try
'define the two values for your Server
port = 1234
localAddr = IPAddress.Loopback 'loopbak = 127.0.0.1 = myself
clientListener = New TcpListener(localAddr, 4321)
client = New TcpClient(localAddr.ToString, port)
Return "Connected to the server"
Catch ex As Exception
Return ex.Message
End Try
End Function
Public Function receive() As String
Try
clientListener.Start()
Dim mySocket As Socket
mySocket = clientListener.AcceptSocket()
Dim recieveBuff(225) As Byte
mySocket.Receive(recieveBuff, recieveBuff.Length, SocketFlags.None)
Dim str As String = System.Text.Encoding.ASCII.GetString(recieveBuff, 0, recieveBuff.Length).Trim(Microsoft.VisualBasic.ChrW(0))
Return str
mySocket.Receive(recieveBuff, recieveBuff.Length, SocketFlags.None)
str = System.Text.Encoding.ASCII.GetString(recieveBuff, 0, recieveBuff.Length).Trim(Microsoft.VisualBasic.ChrW(0))
clientListener.Stop()
Catch exp As Exception
Return "Exception: " + exp.Message
End Try
End Function
End Class
Or use BeginAcceptSocket, but you'll have to move your receive code to the callback.
mySocket = clientListener.AcceptSocket()
These lines block further action untill a socket has been acepted, it will block your code until a socket has been accepted. Use thread to prevent blocking

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.