Test telnet communication on remote computer using VB.net? - vb.net

I have a central server and I need to write a bit of vb.net which will see if I can telnet to a specified server on a specified port.
Is there anyway this can be done in VB.net? I thought about sending command prompts to the remote server to execute telnet, then output the logs of netsh and read those and send the information back to the central server for review.
Its a very messy way of doing it, so I was just wondering if there was an easier way

You should just create a TcpClient object with the IP address of the target server and port (typically 23 for telnet). Then call Connect!
See here for more info:
http://msdn.microsoft.com/en-us/library/system.net.sockets.tcpclient.aspx
Something like this (may not be exact):
Try
Dim telnetServerIp As String = "192.168.100.55"
Dim telnetPort As Integer = 23
Dim client As New TcpClient(telnetServerIp, telnetPort)
MessageBox.Show("Server is reachable")
Catch ex As Exception
MessageBox.Show("Could not reach server")
End Try
Be advised this is sample code. You'd want to clean up (close/dispose) the connection (TcpClient) object when you were done, etc. But it should get you started.

You should try something to implement this. there are lots help available for Telnet communication using .net.
Take idea from these specified links and implement in vb.net..
How can I open a telnet connection and run a few commands in C#
Telnet connection using .net
You can use a System.Net.Sockets.TcpClient object instead of a
socket object, which already has the socket parameters configured to
use ProtocolType.Tcp
1.Create a new TcpClient object, which takes a server name and a port (no IPEndPoint necessary, nice).
2.Pull a NetworkStream out of the TcpClient by calling GetStream()
3.Convert your message into bytes using Encoding.ASCII.GetBytes(string)
4.Now you can send and receive data using the stream.Write and stream.Read methods, respectively. The stream.Read method returns the number of bytes written to your receiving array, by the way.
5.Put the data back into human-readable format using Encoding.ASCII.GetString(byte array).
6.Clean up your mess before the network admins get mad by calling stream.Close() and client.Close().
Ref:C# 2.0* and Telnet - Not As Painful As It Sounds
// 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.
Int32 port = 13000;
TcpClient client = new TcpClient(server, port);
// Translate the passed message into ASCII and store it as a Byte array.
Byte[] data = System.Text.Encoding.ASCII.GetBytes(message);
// Get a client stream for reading and writing.
// Stream stream = client.GetStream();
NetworkStream stream = client.GetStream();
// Send the message to the connected TcpServer.
stream.Write(data, 0, data.Length);
Console.WriteLine("Sent: {0}", message);

I made this for a project at work.
I think it's a complete general solution for most people's needs
However, This is my first real .net project so feel free to critique it.
Modeled on http://www.codeproject.com/Articles/63201/TelnetSocket
Imports System.Threading
Imports System.IO
Imports System.IO.Pipes
Public Class TelnetClient
Private Server As String
Private NetWorkProtocolClient As System.Net.Sockets.TcpClient
Private ServerStream As System.Net.Sockets.NetworkStream
Private DoReader As Boolean
Private ReaderThread As Thread
Private OutputPipe As AnonymousPipeServerStream
Private WaitForString As String
Private WaitForStringEvent As New AutoResetEvent(False)
ReadOnly Property IsConnected() As Boolean
Get
Return (Not (IsNothing(NetWorkProtocolClient)) AndAlso (NetWorkProtocolClient.Connected))
End Get
End Property
ReadOnly Property ConnectedTo() As String
Get
If (Not (IsNothing(NetWorkProtocolClient)) AndAlso (NetWorkProtocolClient.Connected)) Then
Return NetWorkProtocolClient.Client.RemoteEndPoint.ToString()
Else
Return "Nothing"
End If
End Get
End Property
'Set the Server string to connect to.
Public Sub SetServer(ByVal new_server As String)
'double check this later
Server = new_server
End Sub
'Connects if possilbe. If already conneced to some thing it Disconnects from old Telnet and connects to new Telnet.
Public Sub Connect()
Try
If (Not (IsNothing(NetWorkProtocolClient))) AndAlso NetWorkProtocolClient.Connected Then
Disconnect()
End If
If Not IsNothing(Server) Then
NetWorkProtocolClient = New System.Net.Sockets.TcpClient(Server, 23)
If NetWorkProtocolClient.Connected Then
'clear on a new client
WaitForString = Nothing
WaitForStringEvent.Reset()
NetWorkProtocolClient.NoDelay = True
ServerStream = NetWorkProtocolClient.GetStream()
ServerStream.ReadTimeout = 1000
DoReader = True
ReaderThread = New Thread(AddressOf ReaderTask)
ReaderThread.IsBackground = True
ReaderThread.Priority = ThreadPriority.AboveNormal
ReaderThread.Start()
End If
End If
Catch ex As System.Net.Sockets.SocketException
Console.WriteLine("SocketException Connect: {0}", ex)
End Try
End Sub
'Disconnects if connected, otherwise does nothing.
Public Sub Disconnect()
Try
If ReaderThread.IsAlive Then
DoReader = False
ReaderThread.Join(1000)
End If
If (Not (IsNothing(NetWorkProtocolClient))) Then
ServerStream.Close()
NetWorkProtocolClient.Close()
End If
Catch ex As System.Net.Sockets.SocketException
Console.WriteLine("SocketException Disconnect: {0}", ex)
End Try
End Sub
'Returns true if found before timeout milliseconds. Use -1 to have infinite wait time.
'Returns false if timeout occured.
Public Function WaitFor(ByVal command As String, ByVal timeout As Integer) As Boolean
WaitForString = New String(command)
WaitForStringEvent.Reset()
Dim was_signaled As Boolean = False
'Block until a the right value from reader or user defined timeout
was_signaled = WaitForStringEvent.WaitOne(timeout)
WaitForString = Nothing
Return was_signaled
End Function
Public Sub Write(ByVal command As String)
Try
If (Not (IsNothing(NetWorkProtocolClient))) Then
If NetWorkProtocolClient.Connected Then
'Write the value to the Stream
Dim bytes() As Byte = System.Text.Encoding.ASCII.GetBytes(command)
SyncLock ServerStream
ServerStream.Write(bytes, 0, bytes.Length)
End SyncLock
End If
End If
Catch ex As System.Net.Sockets.SocketException
Console.WriteLine("SocketException Write: {0}", ex)
End Try
End Sub
'appends CrLf for the caller
Public Sub WriteLine(ByVal command As String)
Try
If (Not (IsNothing(NetWorkProtocolClient))) Then
If NetWorkProtocolClient.Connected Then
'Write the value to the Stream
Dim bytes() As Byte = System.Text.Encoding.ASCII.GetBytes(command & vbCrLf)
SyncLock ServerStream
ServerStream.Write(bytes, 0, bytes.Length)
End SyncLock
End If
End If
Catch ex As System.Net.Sockets.SocketException
Console.WriteLine("SocketException Write: {0}", ex)
End Try
End Sub
'Get a pipe to read output. Note: anything written by WriteLine may be echoed back if the other Telnet offers to do it.
Public Function GetPipeHandle() As String
If Not IsNothing(ReaderThread) AndAlso ReaderThread.IsAlive AndAlso Not IsNothing(OutputPipe) Then
Return OutputPipe.GetClientHandleAsString
Else
Return Nothing
End If
End Function
'Task that watches the tcp stream, passes info to the negotiation function and signals the WaitFor task.
Private Sub ReaderTask()
Try
OutputPipe = New AnonymousPipeServerStream(PipeDirection.Out)
Dim prevData As New String("")
While (DoReader)
If (Not (IsNothing(NetWorkProtocolClient))) Then
If ServerStream.DataAvailable Then
'Grab Data
Dim data As [Byte]() = New [Byte](NetWorkProtocolClient.ReceiveBufferSize) {}
Dim bytes As Integer = ServerStream.Read(data, 0, data.Length)
'Negotiate anything that came in
bytes = Negotiate(data, bytes)
If (bytes > 0) Then
'append previous to the search sting incase messages were fragmented
Dim s As New String(prevData & System.Text.ASCIIEncoding.ASCII.GetChars(data))
'If Pipe is connected send it remaining real data
If OutputPipe.IsConnected Then
OutputPipe.Write(data, 0, bytes)
End If
'Check remaining against WaitForString
If Not IsNothing(WaitForString) Then
If s.Contains(WaitForString) Then
WaitForStringEvent.Set()
'clear prevData buffer because the WaitForString was found
prevData = New String("")
Else
'Nothing found make the current string part of the next string.
prevData = New String(s)
End If
Else
prevData = New String("")
End If
End If
Else
Thread.Sleep(100)
End If
End If
End While
OutputPipe.Close()
OutputPipe.Dispose()
Catch ex As System.IO.IOException
Console.WriteLine("IO Error: {0}", ex)
Catch ex As System.Net.Sockets.SocketException
Console.WriteLine("SocketException Reader: {0}", ex)
End Try
End Sub
'Shamelessly adapted from http://www.codeproject.com/Articles/63201/TelnetSocket
'The basic algorithm used here is:
' Iterate across the incoming bytes
' Assume that an IAC (byte 255) is the first of a two- or three-byte Telnet command and handle it:
' If two IACs are together, they represent one data byte 255
' Ignore the Go-Ahead command
' Respond WONT to all DOs and DONTs
' Respond DONT to all WONTs
' Respond DO to WILL ECHO and WILL SUPPRESS GO-AHEAD
' Respond DONT to all other WILLs
' Any other bytes are data; ignore nulls, and shift the rest as necessary
' Return the number of bytes that remain after removing the Telnet command and ignoring nulls
Private Function Negotiate(ByVal data As Byte(), ByVal length As Int32) As Int32
Dim index As Int32 = 0
Dim remaining As Int32 = 0
While (index < length)
If (data(index) = TelnetBytes.IAC) Then
Try
Select Case data(index + 1)
Case TelnetBytes.IAC
data(remaining) = data(index)
remaining += 1
index += 2
Case TelnetBytes.GA
index += 2
Case TelnetBytes.WDO
data(index + 1) = TelnetBytes.WONT
SyncLock ServerStream
ServerStream.Write(data, index, 3)
End SyncLock
index += 3
Case TelnetBytes.DONT
data(index + 1) = TelnetBytes.WONT
SyncLock ServerStream
ServerStream.Write(data, index, 3)
End SyncLock
index += 3
Case TelnetBytes.WONT
data(index + 1) = TelnetBytes.DONT
SyncLock ServerStream
ServerStream.Write(data, index, 3)
End SyncLock
index += 3
Case TelnetBytes.WILL
Dim action As Byte = TelnetBytes.DONT
Select Case data(index + 2)
Case TelnetBytes.ECHO
action = TelnetBytes.WDO
Case TelnetBytes.SUPP
action = TelnetBytes.WDO
End Select
data(index + 1) = action
SyncLock ServerStream
ServerStream.Write(data, index, 3)
End SyncLock
index += 3
End Select
Catch ex As System.IndexOutOfRangeException
index = length
End Try
Else
If (data(index) <> 0) Then
data(remaining) = data(index)
remaining += 1
End If
index += 1
End If
End While
Return remaining
End Function
Private Structure TelnetBytes
'Commands
Public Const GA As Byte = 249
Public Const WILL As Byte = 251
Public Const WONT As Byte = 252
Public Const WDO As Byte = 253 'Actually just DO but is protected word in vb.net
Public Const DONT As Byte = 254
Public Const IAC As Byte = 255
'Options
Public Const ECHO As Byte = 1
Public Const SUPP As Byte = 3
End Structure
End Class

Related

vb.net - receiving hex data over serial interface

I do have a device, which I communicate with over the serial Interface.
The communication is done in hex, so I send hex and I do receive hex.
Example: if I send "AA 00 03 89 18 0A 98 BB" the device reports back with "AA 00 02 00 80 82 BB".
My aim is to get a hand on the return value in an human readable way, respecively as a string.
The sending works fine, however the receiving is the part where I struggle hard and where I need help.
The sending part:
This is the part where I define the command to send:
Public Class ClassRfidWrapper
Public Function Command(ByVal theCommand As String) As Byte()
'Versuche.
Try
If theCommand = "SetBuzzer" Then
Dim bytes() As Byte = {&HAA, &H0, &H3, &H89, &H18, &HA, &H98, &HBB}
Return bytes
End If
Catch ex As Exception
Console.ForegroundColor = ConsoleColor.Red
Console.WriteLine("Class -> ClassRfidWrapper, Method -> SendCommand, Error -> " & ex.Message)
End Try
Return Nothing
End Function
End Class
This is the part where I send the hex message to the device:
Public Sub MySendSerialData(ByVal data As Byte())
'Versuche.
Try
If MyCheckIfSerialIsConnected() = True Then
'Mitteilung.
Main.MessageObject.MyMessage("message sent to device: ", Bytes_To_String2(data), 3)
'Log [LogWrapperToDevice]
Main.LogObject.MyLog(Bytes_To_String2(data), "LogWrapperToDevice")
SerialInterface.Write(data, 0, data.Length)
End If
Catch ex As Exception
Console.ForegroundColor = ConsoleColor.Red
Console.WriteLine("Class -> ClassSerialInterface, Method -> MySendSerialData, Error -> " & ex.Message)
End Try
End Sub
Do the sending:
SerialInterfaceObject.MySendSerialData(RfidWrapperObject.Command("SetBuzzer"))
Function to convert Hex to string:
Public Function Bytes_To_String2(ByVal bytes_Input As Byte()) As String
Dim strTemp As New StringBuilder(bytes_Input.Length * 2)
For Each b As Byte In bytes_Input
strTemp.Append(Conversion.Hex(b))
Next
Return strTemp.ToString()
End Function
The receiving part:
This is where I have the problems
Public Shared Sub DataReceivedHandler(sender As Object, e As SerialDataReceivedEventArgs)
Dim sp As SerialPort = CType(sender, SerialPort)
Dim data As String = sp.ReadExisting()
'Mitteilung.
Main.MessageObject.MyMessage("incoming serial data: ", CStr(data), 3)
'Log [LogDeviceToWrapper]
Main.LogObject.MyLog(CStr(data), "LogDeviceToWrapper")
End Sub
The problem is, I get garbage...
I understand, that .ReadExisting is the wrong way, as it interprets the received data as string, so I need an example code, of how to receive and convert the data to a byte array containing hex code, which I can subsequently convert to a string with my function Bytes_To_String2
Thanks for your help
Read the response buffer as a byte array.
Public Shared Sub DataReceivedHandler(sender As Object, e As SerialDataReceivedEventArgs)
Dim sp As SerialPort = CType(sender, SerialPort)
Dim respSize As Integer = sp.BytesToRead
Dim respBuffer As Byte() = New Byte(respSize - 1)
comport.Read(respBuffer, 0, respSize)
' Convert to string and additional processing ...
End Sub

Dropbox error using upload session

This is the modified code about uploadsession soo at small size file it working like a charm but when I try larger file like 5mb up. The following error keep showing up :
+$exception {"lookup_failed/closed/..."} System.Exception {Dropbox.Api.ApiException}
Private Async Sub UploadToolStripMenuItem2_Click(sender As Object, e As EventArgs) Handles UploadToolStripMenuItem2.Click
Dim C As New OpenFileDialog
C.Title = "Choose File"
C.Filter = "All Files (*.*)|*.*"
If C.ShowDialog = Windows.Forms.DialogResult.OK Then
Dim fileinfos = Path.GetFileName(C.FileName)
Dim filetempat = Path.GetFullPath(C.FileName)
Dim tempat As String = direktori.Text & "/" & fileinfos
Await Upload(filetempat, tempat)
End If
End Sub
Async Function Upload(localPath As String, remotePath As String) As Task
Const ChunkSize As Integer = 4096 * 1024
Using fileStream = File.Open(localPath, FileMode.Open)
If fileStream.Length <= ChunkSize Then
Await A.Files.UploadAsync(remotePath, body:=fileStream)
Else
Await Me.ChunkUpload(remotePath, fileStream, ChunkSize)
End If
End Using
End Function
Private Async Function ChunkUpload(path As [String], stream As FileStream, chunkSize As Integer) As Task
Dim numChunks As Integer = CInt(Math.Ceiling(CDbl(stream.Length) / chunkSize))
Dim buffer As Byte() = New Byte(chunkSize - 1) {}
Dim sessionId As String = Nothing
For idx As Integer = 0 To numChunks - 1
Dim byteRead = stream.Read(buffer, 0, chunkSize)
Using memStream = New MemoryStream(buffer, 0, byteRead)
If idx = 0 Then
Dim result = Await A.Files.UploadSessionStartAsync(True, memStream)
sessionId = result.SessionId
kondisi.Text=byteRead
Else
Dim cursor = New UploadSessionCursor(sessionId, CULng(CUInt(chunkSize) * CUInt(idx)))
If idx = numChunks - 1 Then
Dim fileMetadata As FileMetadata = Await A.Files.UploadSessionFinishAsync(cursor, New CommitInfo(path), memStream)
MessageBox.Show("Upload Complete")
Console.WriteLine(fileMetadata.PathDisplay)
Else
Await A.Files.UploadSessionAppendV2Async(cursor, True, memStream)
MessageBox.Show("Upload Failed")
End If
End If
End Using
Next
End Function
okay now its fixed, but when i got home, and try this code at my home,i got error, is this method are affected by slow internet connection ?.cause my campus have a decent speed.
this is the error message
+$exception {"Cannot access a disposed object.\r\nObject name: 'System.Net.Sockets.Socket'."} System.Exception {System.ObjectDisposedException}
this Cannot obtain value of local or argument '<this>' as it is not available at this instruction pointer, possibly because it has been optimized away. System.Net.Sockets.Socket
asyncResult Cannot obtain value of local or argument 'asyncResult' as it is not available at this instruction pointer, possibly because it has been optimized away. System.IAsyncResult
errorCode Cannot obtain value of local or argument 'errorCode' as it is not available at this instruction pointer, possibly because it has been optimized away. System.Net.Sockets.SocketError
this error window i got
A first chance exception of type 'System.ObjectDisposedException' occurred in System.dll
Additional information: Cannot access a disposed object.
This Closed error indicates you can't continue uploading to the upload session because it's already been closed.
The UploadSessionStartAsync and UploadSessionAppendV2Async both take a bool parameter called close, which closes the session.
You're always setting that to True when you call those, closing the sessions. You shouldn't close a session until you're finished uploading data for it.

visual basic .NET get user input without pressing enter

I know of the existence of the code character = System.Console.ReadKey().tostring.
This will read one character.
Also in another stack overflow post I found:
Public Shared Function ReadPipedInfo() As StreamReader
'call with a default value of 5 milliseconds
Return ReadPipedInfo(5000)
End Function
Public Shared Function ReadPipedInfo(waitTimeInMilliseconds As Integer) As StreamReader
'allocate the class we're going to callback to
Dim callbackClass As New ReadPipedInfoCallback()
'to indicate read complete or timeout
Dim readCompleteEvent As New AutoResetEvent(False)
'open the StdIn so that we can read against it asynchronously
Dim stdIn As Stream = Console.OpenStandardInput()
'allocate a one-byte buffer, we're going to read off the stream one byte at a time
Dim singleByteBuffer As Byte() = New Byte(0) {}
'allocate a list of an arbitary size to store the read bytes
Dim byteStorage As New List(Of Byte)(4096)
Dim asyncRead As IAsyncResult = Nothing
Dim readLength As Integer = 0
'the bytes we have successfully read
Do
'perform the read and wait until it finishes, unless it's already finished
asyncRead = stdIn.BeginRead(singleByteBuffer, 0, singleByteBuffer.Length, New AsyncCallback(AddressOf callbackClass.ReadCallback), readCompleteEvent)
If Not asyncRead.CompletedSynchronously Then
readCompleteEvent.WaitOne(waitTimeInMilliseconds)
End If
'end the async call, one way or another
'if our read succeeded we store the byte we read
If asyncRead.IsCompleted Then
readLength = stdIn.EndRead(asyncRead)
'If readLength > 0 Then
byteStorage.Add(singleByteBuffer(0))
'End If
End If
Loop While asyncRead.IsCompleted AndAlso readLength > 0
'we keep reading until we fail or read nothing
'return results, if we read zero bytes the buffer will return empty
Return New StreamReader(New MemoryStream(byteStorage.ToArray(), 0, byteStorage.Count))
End Function
Private Class ReadPipedInfoCallback
Public Sub ReadCallback(asyncResult As IAsyncResult)
'pull the user-defined variable and strobe the event, the read finished successfully
Dim readCompleteEvent As AutoResetEvent = TryCast(asyncResult.AsyncState, AutoResetEvent)
readCompleteEvent.[Set]()
End Sub
End Class
which reads input if the user pressed enter
how could I make some code that reads (multiple) character(s) without letting the user press enter all the time? But instead use time as the indicator to stop reading the console?
You can use System.Console.Read() here. It reads as character from standard input stream. https://msdn.microsoft.com/en-us/library/system.console.read(v=vs.110).aspx
According to here I found out how to deal with it:
Public Module ConsoleHelper
Sub Main()
msgbox(ReadKeyWithTimeOut(10000).key.ToString)
End Sub
Public Function ReadKeyWithTimeOut(timeOutMS As Integer) As ConsoleKeyInfo
Dim timeoutvalue As DateTime = DateTime.Now.AddMilliseconds(timeOutMS)
While DateTime.Now < timeoutvalue
If Console.KeyAvailable Then
Dim cki As ConsoleKeyInfo = Console.ReadKey()
Return cki
Else
System.Threading.Thread.Sleep(100)
End If
End While
Return New ConsoleKeyInfo(" "C, ConsoleKey.Spacebar, False, False, False)
End Function
End Module
Now just finding out how to give attribute key NULL or something if it timed out.

VB.NET Convert USB as RS232

I have a hardware with USB for communicate between computer to hardware. The vendor not giving any APIs to connect to the device. They give me a protocol. But the protocol is serve for RS232 mode. I ask the vendor whether this protocol can be apply to the USB, they said 'YES'.. So, I'm thirst of idea how to use this protocol. Does anyone know? My old friend said yes I can use the USB and treat is as COM which I need to create an object. Create instance of the object which declare as a serialport as below. But it still can't get the status.
Public Sub New(ByVal intComNumber As Integer, ByVal lngBaudRate As Long, ByVal intDataLng As Integer, ByVal intStopBit As Integer, ByVal intParity As Integer)
Try
objUPSPort = New SerialPort
With objUPSPort
.PortName = ("COM" & intComNumber)
.BaudRate = lngBaudRate
.DataBits = intDataLng
.StopBits = intStopBit
.Parity = intParity
.Handshake = Handshake.None
End With
Catch ex As Exception
MsgBox("Error In Init UPSComm")
End Try
End Sub
Can someone help me identified this? This hardware is UPS. A simple command write to the port. But I get the error when get status. Below is the code to write to the UPS.
Public Function GetStatus() As String
Dim strRet As String
Dim strRecv As String
Dim byteRead() As Byte
Try
If Not IsNothing(objUPSPort) Then
objUPSPort.Open()
objUPSPort.WriteLine("Command will be here" & vbCrLf)
For i = 0 To 100000
If objUPSPort.BytesToRead >= 45 Then
Exit For
End If
Next
ReDim byteRead(objUPSPort.BytesToRead)
objUPSPort.Read(byteRead, 0, objUPSPort.BytesToRead)
strRecv = String.Empty
For i = 0 To byteRead.Length - 1
strRecv = strRecv & Chr(byteRead(i))
Next
If byteRead(38) = 48 Then
MsgBox("Power OK")
ElseIf byteRead(38) = 49 Then
MsgBox("Power Off")
Else
MsgBox("Unknown")
End If
strRet = strRecv
Return strRecv
Else
MsgBox("Error In ComPort Object")
Return String.Empty
End If
Catch ex As Exception
MsgBox("Exception In ComPort Object - " & ex.Message)
Return String.Empty
Finally
objUPSPort.Close()
End Try
End Function
I had few experiences in RS232 comm with USB, as nowadays laptops/pc they dont come with serial port no more. Serial ports usually emulated by USB, using [TTL-to-RS232 transistor, MAX like] some common supplier would use prolific as driver to emulate USB-to-RS232. First you need to know the data type, a simple string or binary.
SerialPorts is event driven, data coming thru the ports can trigger events. I assume to get UPS to send you status, first, you need to send command, as such [some pseudo];
objUPSPort.WriteLine("Command will be here" & vbCrLf)
There two ways to get the data:
Using data receive event driven :
Private Sub objUPSPort_DataReceived(sender As Object, e As IO.Ports.SerialDataReceivedEventArgs) Handles objUPSPort.DataReceived
'call ReceiveData()
End Sub
Create a pooling thread to read data periodically
Private Sub threadUPSReceive()
Do
data = objUPSPort.ReadLine() 'for string
'process the data here or call ReceiveData()
Loop
End Sub
If data stream to be read is binary (similar like yours):
Private Function ReceiveData()
Dim bRead As Integer
Dim returnStr As String = vbEmpty
bRead = objUPSPort.BytesToRead 'Number of Bytes to read
Dim cData(bRead - 1) As Byte
For Each b As Byte In cData
returnStr += Chr(b) 'put data stream in readable ascii
Next
Return returnStr
End Sub
One more thing, make sure the baudrate/stopbit/databit is set correctly.
Hope this help.

Check proxy's from listbox

So i have a listbox that i have there for a list of proxies. I have 4 buttons pertaining to it. they are find, load, save and check
I have the first 3 finished and working but i haven't found anything useful pertaining to checking the proxies, the only one that i found took like 6 seconds per proxy so it took a lot of time for a decent sized list.
So how could i make it that on the press of that button, it checks all of the proxies in the listbox and it deletes the slow ones and the ones that flat out do not work. and does this at a decent pace(so it would probably be multi threaded)
and since i can not figure this out i have no code pertaining to this except for the sub for the button click i do not feel there is a need to post code
My suggestion for you is :
1)use a timer control and set it's Tick property to an appropriate value such 500;
2) create an array of BackGroudWorkers for example BackGroudWorker[20];
3)when your app start run all BackGroudWorkers in array and in tick event of Timer check if any of this BackGroudWorker completed or not.If completed and you have other item in list then run it with new Item.Do this until all list Items checked
Public Shared Function CheckProxy(ByVal Proxy As String) As Boolean
Dim prx As Uri = Nothing
If Uri.TryCreate(Proxy, UriKind.Absolute, prx) Then
Return CheckProxy(prx)
ElseIf Uri.TryCreate("http://" & Proxy, UriKind.Absolute, prx) Then
Return CheckProxy(prx)
Else
Return False
End If
End Function
Public Shared Function CheckProxy(ByVal Proxy As Uri) As Boolean
Dim iProxy As Socket = New Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)
iProxy.ReceiveTimeout = 500 : iProxy.SendTimeout = 500
Try
'' Connect using a timeout (1/2 second)
Dim result As IAsyncResult = iProxy.BeginConnect(Proxy.Host, Proxy.Port, Nothing, Nothing)
Dim success As Boolean = result.AsyncWaitHandle.WaitOne(500, True)
If (Not success) Then
iProxy.Close() : Return False
End If
Catch ex As Exception
Return False
End Try
Dim bytData() As Byte, strData As String
Dim iDataLen As Integer = 1024
strData = String.Format("CONNECT {0}:{1} HTTP/1.0{2}{2}", "www.google.com", 80, vbNewLine)
bytData = System.Text.ASCIIEncoding.ASCII.GetBytes(strData)
If iProxy.Connected Then
iProxy.Send(bytData, bytData.Length, SocketFlags.None)
ReDim bytData(1024)
Do
Try
iDataLen = iProxy.Receive(bytData, bytData.Length, SocketFlags.None)
Catch ex As Exception
iProxy.Close() : Return False
End Try
If iDataLen > 0 Then
strData = System.Text.ASCIIEncoding.ASCII.GetString(bytData)
Exit Do
End If
Loop
Else
Return False
End If
iProxy.Close()
Dim strAttribs() As String
strAttribs = strData.Split(" "c)
If strAttribs(1).Equals("200") Then
Return True
Else
Return False
End If
End Function
You should manage your code for threads etc, as suggested by #Nima for your proxy checking problem I have 2 methods here One asks proxy string and tries to connect it.
e.g.
ProxyStatus = CheckProxy("http://192.168.1.1:8080/")
ProxyStatus is True/False depending on if proxy works or Not