Check proxy's from listbox - vb.net

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

Related

Ping multiple device names (hostname) on the Network

A DataGridView displays hostnames at Column index 0, computer / printer names on the network.
pc1
pc2
print3
pc5
print
....
There are more than 500 such names.
I know how to ping them:
For i = 0 To DataGridView1.Rows.Count - 1
Try
If My.Computer.Network.Ping(DataGridView1.Item(0, i).Value) = True Then
DataGridView1.Rows(i).DefaultCellStyle.BackColor = Color.Lime
Else
DataGridView1.Rows(i).DefaultCellStyle.BackColor = Color.Red
End If
Catch ex As Exception
DataGridView1.Rows(i).DefaultCellStyle.BackColor = Color.Red
End Try
Next
The problem is that the Ping takes a very long time and the application freezes.
How can you speed up this procedure?
And let's say if the node is not available, then simply remove it from the list.
An example to Ping multiple addresses at the same time, using the async version of provided by the Ping class, Ping.SendPingAsync().
This version is await-able, not the same as the Ping.SendAsync() method, still asynchronous but event-driven.
Since you're using a DataGridView to both store the IpAddress/HostName and to present the PingReply results, you need to determine a way to match the Ping result to correct Cell of the DataGridView from which the Ip/Host address was taken.
Here, I'm passing to the method the Row's Index, so when the Ping result comes back, asynchronously, we can match the response to a specific Cell in the DataGridView.
To make the initialization method more generic, I'm passing also the index of the Column where the Ip/Host address is stored and the index of the Column that will show the result (you could also just pass all indexes, not a DataGridView Control reference to the method and handle the results in a different way).
A loop extracts the addresses from the the DataGridView and creates a List(Of Task), adding a PingAsync() Task for each address found.
When the collection is completed, the List(Of Task) is passed to the Task.WhenAll() method, which is then awaited.
This method starts all the Task in the list and returns when all Task have a result.
► Note that the Ping procedure sets a TimeOut, to 5000ms here, so all the Tasks will return before or within that interval, successful or not.
You can then decide if you want to reschedule the failed Pings or not.
The UI update is handled using a Progress delegate. It's just a method (Action delegate) that is called when the Ping procedure has a result to show.
It can also be used when the method that updates the UI runs in a different Thread: the Report() method will call the Progress object delegate in the Thread that created the delegate: the UI Thread, here (in the example, we're not actually ever leaving it, though).
This is how it works:
Assume you're starting the ping sequence from Button.Click event handler.
Note that the handler is declared async.
Private Async Sub btnMassPing_Click(sender As Object, e As EventArgs) Handles btnMassPing.Click
Await MassPing(DataGridView1, 1, 2)
End Sub
Initialization method and IProgress<T> report handler:
Imports System.Drawing
Imports System.Net.NetworkInformation
Imports System.Net.Sockets
Imports System.Threading.Tasks
Private Async Function MassPing(dgv As DataGridView, statusColumn As Integer, addressColumn As Integer) As Task
Dim obj = New Object()
Dim tasks = New List(Of Task)()
Dim progress = New Progress(Of (sequence As Integer, reply As Object))(
Sub(report)
SyncLock obj
Dim status = IPStatus.Unknown
If TypeOf report.reply Is PingReply Then
status = DirectCast(report.reply, PingReply).Status
ElseIf TypeOf report.reply Is SocketError Then
Dim socErr = DirectCast(report.reply, SocketError)
status = If(socErr = SocketError.HostNotFound,
IPStatus.DestinationHostUnreachable,
IPStatus.Unknown)
End If
Dim color As Color = If(status = IPStatus.Success, Color.Green, Color.Red)
Dim cell = dgv(statusColumn, report.sequence)
cell.Style.BackColor = color
cell.Value = If(status = IPStatus.Success, "Online", status.ToString())
End SyncLock
End Sub)
For row As Integer = 0 To dgv.Rows.Count - 1
If row = dgv.NewRowIndex Then Continue For
Dim ipAddr = dgv(addressColumn, row).Value.ToString()
tasks.Add(PingAsync(ipAddr, 5000, row, progress))
Next
Try
Await Task.WhenAll(tasks)
Catch ex As Exception
' Log / report the exception
Console.WriteLine(ex.Message)
End Try
End Function
PingAsync worker method:
Private Async Function PingAsync(ipAddress As String, timeOut As Integer, sequence As Integer, progress As IProgress(Of (seq As Integer, reply As Object))) As Task
Dim buffer As Byte() = New Byte(32) {}
Dim ping = New Ping()
Try
Dim options = New PingOptions(64, True)
Dim reply = Await ping.SendPingAsync(ipAddress, timeOut, buffer, options)
progress.Report((sequence, reply))
Catch pex As PingException
If TypeOf pex.InnerException Is SocketException Then
Dim socEx = DirectCast(pex.InnerException, SocketException)
progress.Report((sequence, socEx.SocketErrorCode))
End If
Finally
ping.Dispose()
End Try
End Function

I need to use Async/Await in my already running program to make it faster

I am having a program in VB, which searches for image in a website as follows:
www.website.com/1.jpg | www.website.com/2.jpg | www.website.com/3.jpg
in loop, and the program opens up only 3.jpg in browser, since 1 and 2 jpg does not exit in server. The program is up and running, but is very very slow, around 120 searches in a minute. However one of my colleagues designed the same program in Angular and that program is running very fast, around 500/600 searches in a minute.
He told me, what he did is generated 50 asynchronous calls to server, and then again 50, and then again 50 and went on like this. thus making his program very fast and ovbiously accurate.
I studied and learnt, that in Visual Basic too, we have async and wait calls to server request, but I cannot figure out how.
Here goes my existing code. Can anyone help me.
Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
Dim MYURL as string
itemsF = 0
While Not itemsF = 50000
MYURL = "www.website.com/" & itemsF & ".jpg"
CheckPageExists(MYURL)
itemsF=itemsF+1
End While
End Sub
Private Function CheckPageExists(ByVal url As String) As Boolean
Dim request As Net.HttpWebRequest
Dim response As Net.HttpWebResponse
request = Net.WebRequest.Create(url)
request.Timeout = 5000
Try
response = request.GetResponse()
Catch ex As Exception
'IMAGE DOES NOT EXITS
Exit Function
End Try
Process.Start(url)
End Function
First, you have to make CheckPageExists an Async method:
Private Async Function CheckPageExists(ByVal url As String) As Task(Of Boolean)
Dim request As Net.HttpWebRequest = Net.WebRequest.Create(url)
request.Timeout = 5
Dim Result As Boolean
Try
Using response As HttpWebResponse = Await request.GetResponseAsync.ConfigureAwait(False)
Using responseReader As New IO.StreamReader(response.GetResponseStream)
Dim actualResponse As String = Await responseReader.ReadToEndAsync
Result = True
End Using
End Using
Catch ex As Exception
'IMAGE DOES NOT EXITS
Result = False
End Try
Console.WriteLine(url)
''Process.Start("chrome.exe", url)
Return Result
End Function
As you can see, instead of GetResponse we are using GetResponseAsync, which is Async itself. This method is very similar to what you were doing before, I
just added Return statements for clarity and a StreamReader to read the response of your website.
Once you've done that, you just need to change your Button2_Click method to call this other method, which incorporates all you were doing before:
Async Function MakeRequests() As Task
Dim tasks As List(Of Task(Of Boolean)) = New List(Of Task(Of Boolean))
Dim itemsF As Integer = 5
For i = 1 To itemsF
Dim MYURL As String = "http://www.touchegolfschool.com/images/" & i & ".jpg"
tasks.Add(CheckPageExists(MYURL))
Next
While tasks.Select(Function(x) x.Result).Count < tasks.Count
Thread.Sleep(100)
End While
End Function
The main change was adding tasks.Select(Function(x) x.Result).Count < tasks.Count; what you were seeing before was a request made but never returning because of the time it took to return; telling the main function to wait until all requests have a result makes the application wait long enough for the responses to come.
Here the main difference is the use of Tasks.
Check this for official documentation on asynchronous programming.

How to detect/identify a serial port programatically in a winform?

I am programming a windows form that will communicate with a microcontroller.
After the winform is loaded, it should automatically detect the comport where the microcontroller is connected .
What I am doing is:
- Get the names of the available ports
- with a loop through these names :
- assign the port name to the serial port instance in the form
- send a command for the detection
- wait some time
- check if some text has been received
- compare the received message to the identification message
- if it is the right one break the loop and return the result, if not
continue
Below is the code of the function. I am using thread.sleep method. But the function is not working and I don't detect the board when it is there.
Can You tell me what is wrong with the function? Is the time delay blocking the reception? how should I ameliorate it?
This function is excuted at the beginning after loading the form. If I don't find the port, nothing can go forward. On the other side, there are no other threads I have to take into account at that stage of the excution. I thought about the DatarRceived Event, but it does not make sense at this stage, it will be activated after the right port has been detected.
Please let me know what you think
thank you
Public Function connect(testport As SerialPort, recognizeText As String, userCommand As String) As Boolean
Dim intReturnASCII As Integer = 0
Dim charReturnValue = Chr(intReturnASCII)
Dim returnMessage As String = ""
Dim count As Integer = 0
Dim ports As String() = IO.Ports.SerialPort.GetPortNames
If testport.IsOpen Then
testport.Close()
End If
Try
For Each newport As String In ports
testport.PortName = newport
testport.Open()
testport.Write(STX & userCommand & ETX)
Thread.Sleep(200) ' stop the userform and wait for the reception of the response
count = testport.BytesToRead
While count > 0
intReturnASCII = testport.ReadByte
returnMessage = returnMessage + Convert.ToChar(intReturnASCII)
count -= 1
End While
testport.Close()
XMCPort = newport ' Danach instantiate the serial port publicly with port name , is true instantiate
If returnMessage.Contains(recognizeText) Then
Return True
End If
Next
Return False
Catch ex As Exception
Return False
End Try
count = 0
returnMessage = ""
End Function

Pass Dynamic connection string to another Windows Form (VB.NET)

I am creating a windows application which required Dynamic Connection String in the app starting (user need to provide db credentials through a form), After entering the connection credentials user redirected to new win form
Everything is working fine but how can I pass my dynamic connection to another form.
I tried to save it to App variable but I couldn't (I think its read only)
Also I tried save it to registry but can't retrieve values.
Is there any other option available ? like writing & retrieving ConString to a text file or XML
Thanks
This how you can get and set registry values :
Public Function GetRegistryValue(ByVal KeyName As String, Optional ByVal DefaultValue As Object = Nothing) As Object
Dim res As Object = Nothing
Try
Dim k = My.Computer.Registry.CurrentUser.OpenSubKey("Software\YourAppName", True)
If k IsNot Nothing Then
res = k.GetValue(KeyName, DefaultValue)
Else
k = My.Computer.Registry.CurrentUser.CreateSubKey("Software\YourAppName")
End If
If k IsNot Nothing Then k.Close()
Catch ' ex As Exception
'PromptMsg(ex)
End Try
Return res
End Function
Public Sub SetRegistryValue(ByVal KeyName As String, ByVal _Value As Object)
Try
Dim k = My.Computer.Registry.CurrentUser.OpenSubKey("Software\YourAppName", True)
If k IsNot Nothing Then
k.SetValue(KeyName, _Value)
Else
k = My.Computer.Registry.CurrentUser.CreateSubKey("Software\YourAppName")
k.SetValue(KeyName, _Value)
End If
If k IsNot Nothing Then k.Close()
Catch ' ex As Exception
'PromptMsg(ex)
End Try
End Sub
It's working a 100%, If you please mark this answer as Right

Test telnet communication on remote computer using 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