VB.NET How To Continuously Read TCP Stream - vb.net

Morning,
After much mucking around I have finally got my little TCP Listener application to connect to my server and listen to the traffic.
I am able to connect and get the initial response from the port however it does not return the stream traffic constantly, I need to constantly monitor the ports traffic so I can effectively post it to a database, can anyone help me with how I would loop this?
Here is my code at the moment:
Imports System
Imports System.Net
Imports System.Net.Sockets
Imports System.Runtime.InteropServices ' DllImport
Imports System.Security.Principal ' WindowsImpersonationContext
Imports System.Text
Public Class Form1
Private Delegate Sub AppendTextBoxDelegate(ByVal TB As RichTextBox, ByVal txt As String)
Private Sub AppendTextBoxes(ByVal TB As RichTextBox, ByVal txt As String)
If TB.InvokeRequired Then
TB.Invoke(New AppendTextBoxDelegate(AddressOf AppendTextBoxes), New Object() {TB, txt})
Else
TB.Text = ""
TB.Text = RichTextBox1.Text + Environment.NewLine + " >> " + txt
End If
End Sub
Dim clientSocket As New System.Net.Sockets.TcpClient()
Dim serverStream As NetworkStream
Private Sub Button1_Click(ByVal sender As System.Object, _
ByVal e As System.EventArgs) Handles Button1.Click
BackgroundWorker1.RunWorkerAsync()
End Sub
Private Sub Form1_Load(ByVal sender As System.Object, _
ByVal e As System.EventArgs) Handles MyBase.Load
AppendTextBoxes(RichTextBox1, "Client Started")
End Sub
Private Sub My_BgWorker_DoWork1(ByVal sender As Object, ByVal e As System.ComponentModel.DoWorkEventArgs) Handles BackgroundWorker1.DoWork
Try
clientSocket.Connect("192.168.1.22", 21055)
AppendTextBoxes(RichTextBox1, "Client Socket Program - Server Connected ...")
Dim serverStream As NetworkStream = clientSocket.GetStream()
If serverStream.CanRead Then
Do While clientSocket.Connected
Dim outStream As Byte() = _
System.Text.Encoding.ASCII.GetBytes("Message from Client$")
serverStream.Write(outStream, 0, outStream.Length)
serverStream.Flush()
Dim inStream(10024) As Byte
serverStream.Read(inStream, 0, CInt(clientSocket.ReceiveBufferSize))
Dim returndata As String = _
System.Text.Encoding.ASCII.GetString(inStream)
AppendTextBoxes(RichTextBox1, "Data from Server : " + returndata)
Console.WriteLine("Data from Server : " + returndata)
Loop
Else
AppendTextBoxes(RichTextBox1, "No Data to Receive")
clientSocket.Close()
serverStream.Close()
End If
Catch ex As Exception
MessageBox.Show(Environment.NewLine & ex.Message & Environment.NewLine & ex.StackTrace, "Dumping To Log", MessageBoxButtons.OK, MessageBoxIcon.Error, MessageBoxDefaultButton.Button1)
End Try
End Sub
Private Sub BackgroundWorker1_ProgressChanged(ByVal sender As Object, _
ByVal e As System.ComponentModel.ProgressChangedEventArgs) _
Handles BackgroundWorker1.ProgressChanged
'AppendTextBoxes(RichTextBox1.Text, "DONE!")
'ProgBar.Value = e.ProgressPercentage
End Sub
Private Sub BackgroundWorker1_RunWorkerCompleted(ByVal sender As Object, _
ByVal e As System.ComponentModel.RunWorkerCompletedEventArgs) _
Handles BackgroundWorker1.RunWorkerCompleted
If e.Cancelled Then
MsgBox("Cancelled")
End If
Console.WriteLine("Finished Processing - Background Worker 1")
AppendTextBoxes(RichTextBox1, "Finished Getting Stream!")
End Sub
End Class
Any help is greatly appreciated, this is for a project I need to have in by 1st Jan 2015 :(
James

You have your condition to run while connected which means thats true the first time. Change that to:
Do Until Not Client.Connected

Related

How to save my wlan settings?

I'm currently using Visual Studio 2012. My form code is given below with design screenshots. I am trying to make a virtual hotspot for my PC but I want to add one feature which takes previous SSID and password. My hotspot opens every time with blank text.
Here's my form design:
Form1 Design:
[
Form1 code:
Imports System.Runtime.InteropServices
Imports System.Collections.ObjectModel
Imports System.Text
Imports NativeWifi
Public Class Form1
Public Const WM_NCLBUTTONDOWN As Integer = &HA1
Public Const HT_CAPTION As Integer = &H2`
<DllImportAttribute("user32.dll")> _
Public Shared Function SendMessage(ByVal hWnd As IntPtr, _
ByVal Msg As Integer, ByVal wParam As Integer, _
ByVal lParam As Integer) As Integer
End Function
<DllImportAttribute("user32.dll")> _
Public Shared Function ReleaseCapture() As Boolean
End Function`
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Dim wlan = New WlanClient()
Dim connectedSsids As Collection(Of [String]) = New Collection(Of String)()
For Each wlanInterface As WlanClient.WlanInterface In wlan.Interfaces
Dim ssid As Wlan.Dot11Ssid = wlanInterface.CurrentConnection.wlanAssociationAttributes.dot11Ssid
connectedSsids.Add(New [String](Encoding.ASCII.GetChars(ssid.SSID, 0, CInt(ssid.SSIDLength))))
For Each item As String In connectedSsids
Label1.Text = item
Next
Next
End Sub
Private Sub Form1_MouseDown(ByVal sender As Object, _
ByVal e As System.Windows.Forms.MouseEventArgs) _
Handles Me.MouseDown
If e.Button = Windows.Forms.MouseButtons.Left Then
ReleaseCapture()
SendMessage(Handle, WM_NCLBUTTONDOWN, _
HT_CAPTION, 0)
End If
End Sub
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Try
If Form2.TextBox1.Text = "" Then
MsgBox("Hotspot name cant be empty", MsgBoxStyle.Critical)
End If
If Form2.TextBox2.TextLength < 8 Then
MsgBox("Password should be 8+ character", MsgBoxStyle.Critical)
If Form2.TextBox2.Text = "" Then
MsgBox("Password cant be empty", MsgBoxStyle.Critical)
End If
Else
Dim process As New Process()
process.StartInfo.Verb = "runas"
process.StartInfo.UseShellExecute = True
process.Start("cmd", String.Format("/c {0} & {1} & {2}", "netsh wlan set hostednetwork mode=allow ssid=" & Form2.TextBox1.Text & " key=" & Form2.TextBox2.Text, "netsh wlan start hostednetwork", "pause"))
Form2.CheckBox1.Enabled = False
Form2.TextBox1.Enabled = False
Form2.TextBox2.Enabled = False
MsgBox("Hotspot started Successfully", MsgBoxStyle.Information)
End If
Catch
MsgBox("Failed to Establish a hotspot", MsgBoxStyle.Exclamation)
End Try
End Sub
Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
Process.Start("CMD", "/C netsh wlan stop hostednetwork")
Form2.CheckBox1.Enabled = True
Form2.TextBox1.Enabled = True
Form2.TextBox2.Enabled = True
MsgBox("Hotspot stopped Successfully", MsgBoxStyle.Information)
End Sub
Private Sub Clsbtn_Click(sender As Object, e As EventArgs) Handles Clsbtn.Click
Me.Close()
End Sub
Private Sub Minbtn_Click(sender As Object, e As EventArgs) Handles Minbtn.Click
Me.WindowState = System.Windows.Forms.FormWindowState.Minimized
End Sub
Private Sub Button3_Click_1(sender As Object, e As EventArgs) Handles Button3.Click
Me.Hide()
Form2.Show()
End Sub
End Class
Form2 Design:
[

VB.NET - Working with Multiple Forms

I'm trying to make a login window and a main window. The problem is when I close the login form and show the main window, the whole program stops.
The login form:
Imports System.IO
Imports System.Text
Imports System.Net
Public Class frmLogin
Dim address As String = "http://puu.sh/jKJ**Zq/d613de****29.txt"
Dim client As WebClient = New WebClient()
Private Sub frmLogin_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
'frmMain.Close()
End Sub
Private Sub frmLogin_Close(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Me.FormClosed
frmMain.Show()
End Sub
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
If attemptLogin() Then
MsgBox("Login Successful")
Me.Close()
'frmMain.Show()
Else
MsgBox("Username or password is incorrect")
End If
End Sub
Private Function attemptLogin()
Dim reader As StreamReader = New StreamReader(client.OpenRead(address))
Dim line As String
Dim username As String
Dim password As String
line = reader.ReadLine()
Do While Not line Is Nothing
username = line.Split(":")(0)
password = line.Split(":")(1)
If (username = TextBox1.Text And password = TextBox2.Text) Then
Return True
End If
line = reader.ReadLine()
Loop
reader.Close()
client.Dispose()
Return False
End Function
Private Function Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
Dim client As WebClient = New WebClient()
Dim reader As StreamReader = New StreamReader(client.OpenRead(address))
Dim line As String
line = reader.ReadLine
Do While Not line Is Nothing
line = reader.ReadLine()
Loop
reader.Close()
Dim writer As StreamWriter = New StreamWriter(client.OpenRead(address))
writer.Write(TextBox1.Text & ":" & TextBox2.Text)
writer.Close()
client.Dispose()
Return False
End Function
End Class
The Main Window:
Public Class frmMain
Private Sub frmMain_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Me.Load
'frmMain.Close()
End Sub
Private Sub frmMain_closed(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Me.FormClosing
End Sub
End Class
I am fairly new to VB.NET so sorry about the lack of knowledge/ugly coding. I'm used to programming GUIs in Java.
You need to set your 'Shutdown mode' to 'When last form closes'.
You can find this setting by going to My project and then clicking on Application (the first tab).
You can then find the setting at the bottom.

Visual Basic Pinger

I have this pinger up and running well, but cannot think of a way for the program to tell me if a ping reply has failed. I would like it to display in the listbox when there is an error.
Any help would be greatly appreciated.
Option Explicit On
Option Infer Off
Imports System.Net.NetworkInformation
Imports System.ComponentModel
Public Class Form1
Private WithEvents bwPing As New BackgroundWorker
Private pingTarget As String
Private pingsize As Integer
Private numOfpings As Byte
Dim timeout As Integer
Private Sub Button1_Click(ByVal sender As Object, ByVal e As EventArgs) Handles Button1.Click
' start pinger
bwPing.WorkerReportsProgress = True
bwPing.WorkerSupportsCancellation = True
pingTarget = TextBox2.Text
timeout = ComboBox4.Text
If Not bwPing.IsBusy Then bwPing.RunWorkerAsync()
If ComboBox3.Text & ComboBox1.Text = "" Then
bwPing.CancelAsync()
ListBox1.Items.Add("*****!!!!!***** INVALID ENTRY *****!!!!!*****")
MsgBox(" By failing to prepare, you are preparing to fail. ", MsgBoxStyle.Exclamation)
ElseIf ComboBox3.Text = "" Then
bwPing.CancelAsync()
ListBox1.Items.Add("*****!!!!!***** INVALID ENTRY *****!!!!!*****")
MsgBox(" How many troops are you sending in? ", MsgBoxStyle.Exclamation)
ElseIf ComboBox1.Text = "" Then
bwPing.CancelAsync()
ListBox1.Items.Add("*****!!!!!***** INVALID ENTRY *****!!!!!*****")
MsgBox(" How strong are your soldiers? ", MsgBoxStyle.Exclamation)
Else : numOfpings = CInt(ComboBox3.Text)
pingsize = CInt(ComboBox1.Text)
End If
End Sub
Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
' cancel pinger
bwPing.CancelAsync()
End Sub
Private Sub Button3_Click(ByVal sender As Object, ByVal e As EventArgs) Handles Button3.Click
' clear
ListBox1.Items.Clear()
ComboBox1.Text = ""
ComboBox3.Text = ""
ProgressBar1.Value = 0
End Sub
Private Sub bwPing_DoWork(ByVal sender As Object, ByVal e As DoWorkEventArgs) Handles bwPing.DoWork
' ping worker
Dim worker As BackgroundWorker = CType(sender, BackgroundWorker)
Dim packet(pingsize) As Byte
For i As Integer = 0 To numOfpings - 1
bwPing.ReportProgress(i + 1)
Dim ping As New Ping
Dim reply As PingReply = ping.Send(pingTarget, timeout, packet)
If ComboBox3.Text & ComboBox1.Text = "" Then
bwPing.CancelAsync()
Else
ListBox1.Items.Add("You hit " & pingTarget & " in " & reply.RoundtripTime.ToString() & " ms with " & pingsize & " bytes.")
System.Threading.Thread.Sleep(500)
End If
If worker.CancellationPending Then Exit For
Next
End Sub
Private Sub bwPing_ProgressChanged(ByVal sender As Object, ByVal e As ProgressChangedEventArgs) Handles bwPing.ProgressChanged
' update results
Me.ProgressBar1.Value = e.ProgressPercentage
ProgressBar1.Minimum = 0
ProgressBar1.Maximum = numOfpings
End Sub
Private Sub bwPing_RunWorkerCompleted(ByVal sender As Object, ByVal e As RunWorkerCompletedEventArgs) Handles bwPing.RunWorkerCompleted
' finished
Me.ListBox1.Items.Add("*!* The battle is over, but not the war *!*")
Me.ListBox1.Items.Add("::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::")
bwPing.CancelAsync()
End Sub
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Control.CheckForIllegalCrossThreadCalls = False
End Sub
End Class
In general, try to remember that you can check an object for any events it has. Typically, when an object has a completed event, somewhere in the event args, pertinent things, such as completion status, will be provided to you there, in those arguments. That being said, handle the ping completed event.
Side Note* Setting CheckForIllegalCrossThreadCalls to false is not a good idea, use delegates instead.
Example(for ping)
Option Strict On
Option Explicit On
Option Infer Off
Imports System.Net
Imports System.Net.NetworkInformation
Public Class Form1
Private a As New Ping
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
AddHandler a.PingCompleted, AddressOf a_PingCompleted
End Sub
Private Sub a_PingCompleted(sender As Object, e As PingCompletedEventArgs)
If e.Reply.Status.ToString = "Success" Then
MsgBox("Round Trip Time: " & e.Reply.RoundtripTime.ToString & "ms")
Else
MsgBox(e.Reply.Status.ToString)
End If
End Sub
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
'Google's ip address
a.SendAsync(New IPAddress({74, 125, 224, 105}), 100)
End Sub
End Class

Visual basic ICMP Pinger?

I am building an ICMP Pinger in visual basic.
I would like to be able to determine the destination address, time out, size of packets, and how many packets to send.
I only have a small amount of programming knowledge, does anybody have any suggestions? Or a more efficient way to run the program?
Here is what i have that is working so far.
Option Explicit On
Option Infer Off
Imports System.Net.NetworkInformation
Imports System.ComponentModel
Public Class Form1
Private WithEvents bwPing As New BackgroundWorker
Private pingTarget As String
Private pingsize As Integer
Private numOfpings As Integer
Dim timeout As Integer
Private Sub Button1_Click(ByVal sender As Object, ByVal e As EventArgs) Handles Button1.Click
' start pinger
bwPing.WorkerReportsProgress = True
bwPing.WorkerSupportsCancellation = True
pingTarget = TextBox2.Text
timeout = ComboBox4.Text
If Not bwPing.IsBusy Then bwPing.RunWorkerAsync()
If ComboBox3.Text & ComboBox1.Text = "" Then
bwPing.CancelAsync()
ListBox1.Items.Add("*****!!!!!***** INVALID ENTRY *****!!!!!*****")
MsgBox(" By failing to prepare, you are preparing to fail. ", MsgBoxStyle.Exclamation)
ElseIf ComboBox3.Text = "" Then
bwPing.CancelAsync()
ListBox1.Items.Add("*****!!!!!***** INVALID ENTRY *****!!!!!*****")
MsgBox(" How many troops are you sending in? ", MsgBoxStyle.Exclamation)
ElseIf ComboBox1.Text = "" Then
bwPing.CancelAsync()
ListBox1.Items.Add("*****!!!!!***** INVALID ENTRY *****!!!!!*****")
MsgBox(" How strong are your soldiers? ", MsgBoxStyle.Exclamation)
Else : numOfpings = CInt(ComboBox3.Text)
pingsize = CInt(ComboBox1.Text)
End If
End Sub
Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
' cancel pinger
bwPing.CancelAsync()
End Sub
Private Sub Button3_Click(ByVal sender As Object, ByVal e As EventArgs) Handles Button3.Click
' clear
ListBox1.Items.Clear()
ComboBox1.Text = ""
ComboBox3.Text = ""
ProgressBar1.Value = 0
End Sub
Private Sub bwPing_DoWork(ByVal sender As Object, ByVal e As DoWorkEventArgs) Handles bwPing.DoWork
' ping worker
Dim worker As BackgroundWorker = CType(sender, BackgroundWorker)
Dim packet(pingsize) As Byte
For i As Integer = 0 To numOfpings - 1
bwPing.ReportProgress(i + 1)
Dim ping As New Ping
Dim reply As PingReply = ping.Send(pingTarget, timeout)
If ComboBox3.Text & ComboBox1.Text = "" Then
bwPing.CancelAsync()
Else
ListBox1.Items.Add("You hit " & pingTarget & " in " & reply.RoundtripTime.ToString() & " ms with " & pingsize & " bytes.")
System.Threading.Thread.Sleep(500)
End If
If worker.CancellationPending Then Exit For
Next
End Sub
Private Sub bwPing_ProgressChanged(ByVal sender As Object, ByVal e As ProgressChangedEventArgs) Handles bwPing.ProgressChanged
' update results
Me.ProgressBar1.Value = e.ProgressPercentage
ProgressBar1.Minimum = 0
ProgressBar1.Maximum = numOfpings
End Sub
Private Sub bwPing_RunWorkerCompleted(ByVal sender As Object, ByVal e As RunWorkerCompletedEventArgs) Handles bwPing.RunWorkerCompleted
' finished
Me.ListBox1.Items.Add("*!* The battle is over, but not the war *!*")
bwPing.CancelAsync()
End Sub
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Control.CheckForIllegalCrossThreadCalls = False
End Sub
End Class

MultiThreading and Sockets/TCP [VB.NET]

I started learning about TCP/Sockets yesterday and decided to make a chatbox for a friend and I.
Unfortunately, i am having some difficulties with MultiThreading.
Whenever i am using it, i can no longer receive messages from my friend.
But, if i disable it then, everything works perfectly.
I don't know what's going on here, could somebody help?
Imports System.Net.Sockets
Imports System.Net
Public Class ServerClient
Dim _TCPServer As Socket
Dim _TCPListener As TcpListener
Dim _ListenerThread As System.Threading.Thread
Private Sub btnSend_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnSend.Click
'When Submit is pressed, send some text to the client
Dim bytes() As Byte = System.Text.Encoding.ASCII.GetBytes(txtInput.Text)
txtBox.AppendText(vbCrLf & "Server: " & txtInput.Text)
txtInput.Clear()
_TCPServer.Send(bytes)
End Sub
Private Sub TCPListen()
'If somebody calls port 2424, accept it, unblock the socket and start the timer
_TCPListener = New TcpListener(IPAddress.Any, 2424)
_TCPListener.Start()
_TCPServer = _TCPListener.AcceptSocket()
btnSend.Enabled = True
txtBox.AppendText("Connection Established" & vbCrLf)
_TCPServer.Blocking = False
_Timer.Enabled = True
End Sub
Private Sub _Timer_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles _Timer.Tick
'If data has been sent, receive it
Try
Dim rcvdbytes(_TCPServer.ReceiveBufferSize) As Byte
_TCPServer.Receive(rcvdbytes)
txtBox.AppendText(vbCrLf & "Client: " & System.Text.Encoding.ASCII.GetString(rcvdbytes) & vbCrLf)
Catch ex As Exception
End Try
End Sub
Private Sub ServerClient_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
'Link the new thread to TCPListen(), allow access to all threads and wait for a call
_ListenerThread = New Threading.Thread(AddressOf TCPListen)
Control.CheckForIllegalCrossThreadCalls = False
txtBox.AppendText("Waiting for connection.." & vbCrLf)
btnSend.Enabled = False
_ListenerThread.Start()
End Sub
End Class
This example project contains four classes - TcpCommServer, TcpCommClient, clsAsyncUnbuffWriter and CpuMonitor. With these classes, you will not only be able to instantly add TCP/IP functionality to your VB.NET applications, but also has most of the bells and whistles we're all looking for. With these classes, you will be able to connect multiple clients to the server on the same port. You will be able to easily: throttle bandwidth to the clients, and send and receive files and data (text?) along 250 provided channels simultaneously on a single connection.
http://www.codeproject.com/Articles/307315/Reusable-multithreaded-tcp-client-and-server-class
Well, i learned BackgroundWorkers could do the exact same thing and now it all works.
Private Sub ServerClient_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
'Wait for a call
BackgroundWorker1.RunWorkerAsync()
End Sub
Private Sub BackgroundWorker1_DoWork(ByVal sender As System.Object, ByVal e As System.ComponentModel.DoWorkEventArgs) Handles BackgroundWorker1.DoWork
TCPListen()
End Sub
Private Sub BackgroundWorker1_RunWorkerCompleted(ByVal sender As System.Object, ByVal e As System.ComponentModel.RunWorkerCompletedEventArgs) Handles BackgroundWorker1.RunWorkerCompleted
_Timer.Enabled = True
End Sub