VB.NET TCP Server/Client - Get IP of connected client - vb.net

I'm trying to get the IP address of the connected client but I don't know what I doing wrong. Where I can find it? I think near Sub AcceptClient. I was trying to convert cClient to string, but it always results to True or False. I'm trying to get the argument ar from cClient, which gives me an empty result.
Client.Client.RemoteEndPoint doesn't work or I can't use it correctly.
Form1.vb from Server project
Imports System.IO, System.Net, System.Net.Sockets
Public Class Form1
Dim Listener As TcpListener
Dim Client As TcpClient
Dim ClientList As New List(Of ChatClient)
Dim sReader As StreamReader
Dim cClient As ChatClient
Sub xLoad() Handles Me.Load
Listener = New TcpListener(IPAddress.Any, 3818)
Timer1.Start()
Listener.Start()
xUpdate("Server Started", False)
Listener.BeginAcceptTcpClient(New AsyncCallback(AddressOf AcceptClient), Listener)
End Sub
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
''Set view property
ListView1.View = View.Details
ListView1.GridLines = True
ListView1.FullRowSelect = True
'Add column header
ListView1.Columns.Add("Adres IP", 120)
ListView1.Columns.Add("Nazwa użytkownika", 120)
End Sub
Sub AcceptClient(ByVal ar As IAsyncResult)
cClient = New ChatClient(Listener.EndAcceptTcpClient(ar))
AddHandler(cClient.MessageRecieved), AddressOf MessageRecieved
AddHandler(cClient.ClientExited), AddressOf ClientExited
ClientList.Add(cClient)
xUpdate("New Client Joined", True)
Listener.BeginAcceptTcpClient(New AsyncCallback(AddressOf AcceptClient), Listener)
End Sub
Sub MessageRecieved(ByVal Str As String)
xUpdate(Str, True)
End Sub
Sub ClientExited(ByVal Client As ChatClient)
ClientList.Remove(Client)
xUpdate("Client Exited", True)
End Sub
Delegate Sub _xUpdate(ByVal Str As String, ByVal Relay As Boolean)
Sub xUpdate(ByVal Str As String, ByVal Relay As Boolean)
On Error Resume Next
If InvokeRequired Then
Invoke(New _xUpdate(AddressOf xUpdate), Str, Relay)
Else
Dim nStart As Integer
Dim nLast As Integer
If Str.Contains("</>") Then
nStart = InStr(Str, "</></>") + 7
nLast = InStr(Str, "<\><\>")
Str = Mid(Str, nStart, nLast - nStart)
'dzielenie strina po odpowiednim syymbolu na przed i po symbolu :D
Dim mystr As String = Str
Dim cut_at As String = ","
Dim x As Integer = InStr(mystr, cut_at)
Dim string_before As String = mystr.Substring(0, x - 1)
Dim string_after As String = mystr.Substring(x + cut_at.Length - 1)
Dim otherItems As String() = {string_after}
ListView1.Items.Add(string_before).SubItems.AddRange(otherItems) 'use SubItems
ElseIf Str.Contains("<A>") Then
nStart = InStr(Str, "<A>") + 4
nLast = InStr(Str, "<B>")
Str = Mid(Str, nStart, nLast - nStart)
ListBox2.Items.Add(Str & vbNewLine)
Else
TextBox1.AppendText(Str & vbNewLine)
If Relay Then Send(Str & vbNewLine)
End If
End If
End Sub
Private Sub TextBox2_KeyDown(ByVal sender As System.Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles TextBox2.KeyDown
If e.KeyCode = Keys.Enter Then
e.SuppressKeyPress = True
xUpdate("Server Says: " & TextBox2.Text, True)
TextBox2.Clear()
End If
End Sub
Sub Send(ByVal Str As String)
For i As Integer = 0 To ClientList.Count - 1
Try
ClientList(i).Send(Str)
Catch
ClientList.RemoveAt(i)
End Try
Next
End Sub
End Class
ChatClient.vb from Server project
Imports System.Net.Sockets, System.IO
Public Class ChatClient
Public Event MessageRecieved(ByVal Str As String)
Public Event ClientExited(ByVal Client As ChatClient)
Private sWriter As StreamWriter
Public Client As TcpClient
Sub New(ByVal xclient As TcpClient)
Client = xclient
client.GetStream.BeginRead(New Byte() {0}, 0, 0, AddressOf Read, Nothing)
End Sub
Private Sub Read()
Try
Dim sr As New StreamReader(Client.GetStream)
Dim msg As String = sr.ReadLine()
RaiseEvent MessageRecieved(msg)
Client.GetStream.BeginRead(New Byte() {0}, 0, 0, New AsyncCallback(AddressOf Read), Nothing)
Catch
RaiseEvent ClientExited(Me)
End Try
End Sub
Public Sub Send(ByVal Message As String)
sWriter = New StreamWriter(Client.GetStream)
sWriter.WriteLine(Message)
sWriter.Flush()
End Sub
End Class

You can get the IP address from the underlying socket by converting the Socket.RemoteEndPoint property into an IPEndPoint:
Dim Address As IPAddress = CType(cClient.Client.Client.RemoteEndPoint, IPEndPoint).Address
MessageBox.Show(Address.ToString()) 'Example.

Related

How to get ipv4 addresses of all computers on a network in VB.NET

I have a Windows Forms app in Visual basic that is currently sending messages back and forth between two computers. Currently, the user has to manually enter the ipv4 address of the receiver of the message. what I would like to do is put the ipv4 addresses of all the computers on the network into a combo box so the user has a list to pick from.
I have searched a whole bunch of different forums and am unable to find a working solution.
Public Class Form1
Dim strHostName As String
Dim strIPAddress As String
Dim running As Boolean = False
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
strHostName = System.Net.Dns.GetHostName()
strIPAddress = System.Net.Dns.GetHostByName(strHostName).AddressList(0).ToString()
Me.Text = strIPAddress
txtIP.Text = strIPAddress
running = True
'run listener on separate thread
Dim listenTrd As Thread
listenTrd = New Thread(AddressOf StartServer)
listenTrd.IsBackground = True
listenTrd.Start()
End Sub
Private Sub Form1_FormClosing(sender As Object, e As EventArgs) Handles MyBase.FormClosing
running = False
End Sub
Sub StartServer()
Dim serverSocket As New TcpListener(CInt(txtPort.Text))
Dim requestCount As Integer
Dim clientSocket As TcpClient
Dim messageReceived As Boolean = False
While running
messageReceived = False
serverSocket.Start()
msg("Server Started")
clientSocket = serverSocket.AcceptTcpClient()
msg("Accept connection from client")
requestCount = 0
While (Not (messageReceived))
Try
requestCount = requestCount + 1
Dim networkStream As NetworkStream = clientSocket.GetStream()
Dim bytesFrom(10024) As Byte
networkStream.Read(bytesFrom, 0, bytesFrom.Length)
Dim dataFromClient As String = System.Text.Encoding.ASCII.GetString(bytesFrom)
dataFromClient = dataFromClient.Substring(0, dataFromClient.Length)
'invoke into other thread
txtOut.Invoke(Sub()
txtOut.Text += dataFromClient
txtOut.Text += vbNewLine
End Sub)
messageReceived = True
Dim serverResponse As String = "Server response " + Convert.ToString(requestCount)
Dim sendBytes As [Byte]() = Encoding.ASCII.GetBytes(serverResponse)
networkStream.Write(sendBytes, 0, sendBytes.Length)
networkStream.Flush()
Catch ex As Exception
End
End Try
End While
clientSocket.Close()
serverSocket.Stop()
msg("exit")
Console.ReadLine()
End While
End Sub
Sub msg(ByVal mesg As String)
mesg.Trim()
Console.WriteLine(" >> " + mesg)
End Sub
Public Sub WriteData(ByVal data As String, ByRef IP As String)
Try
txtOut.Text += data.PadRight(1)
txtOut.Text += vbNewLine
txtMsg.Clear()
Console.WriteLine("Sending message """ & data & """ to " & IP)
Dim client As TcpClient = New TcpClient()
client.Connect(New IPEndPoint(IPAddress.Parse(IP), CInt(txtPort.Text)))
Dim stream As NetworkStream = client.GetStream()
Dim sendBytes As Byte() = Encoding.ASCII.GetBytes(data)
stream.Write(sendBytes, 0, sendBytes.Length)
Catch ex As Exception
msg(ex.ToString)
End Try
End Sub
Private Sub btnSend_Click(sender As Object, e As EventArgs) Handles btnSend.Click
If Not (txtMsg.Text = vbNullString) AndAlso Not (txtIP.Text = vbNullString) Then
WriteData(txtMsg.Text, txtIP.Text)
End If
End Sub
Private Sub txtMsg_KeyDown(sender As Object, e As KeyEventArgs) Handles txtMsg.KeyDown
If e.KeyCode = Keys.Enter Then
If Not (txtMsg.Text = vbNullString) AndAlso Not (txtIP.Text = vbNullString) Then
WriteData(txtMsg.Text, txtIP.Text)
End If
End If
End Sub
Private Sub BtnFind_Click(sender As Object, e As EventArgs) Handles btnFind.Click
'find all local addresses and put in combobox (button will be removed later)
End Sub
End Class
For PC names "as you suggested in your comments", I used this at work to get pc names i was on domain, try it:
AFAIK it works on domains...
Make sure you have a listbox on your form, or change listbox and populate in your combobox directly, play with that as you like :)
Private Delegate Sub UpdateDelegate(ByVal s As String)
Dim t As New Threading.Thread(AddressOf GetNetworkComputers)
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
t.IsBackground = True
t.Start()
End Sub
Private Sub AddListBoxItem(ByVal s As String)
ListBox1.Items.Add(s)
End Sub
Private Sub GetNetworkComputers()
Try
Dim alWorkGroups As New ArrayList
Dim de As New DirectoryEntry
de.Path = "WinNT:"
For Each d As DirectoryEntry In de.Children
If d.SchemaClassName = "Domain" Then alWorkGroups.Add(d.Name)
d.Dispose()
Next
For Each workgroup As String In alWorkGroups
de.Path = "WinNT://" & workgroup
For Each d As DirectoryEntry In de.Children
If d.SchemaClassName = "Computer" Then
Dim del As UpdateDelegate = AddressOf AddListBoxItem
Me.Invoke(del, d.Name)
End If
d.Dispose()
Next
Next
Catch ex As Exception
'MsgBox(Ex.Message)
End Try
End Sub
POC:

FOR statement conflicting with IF statement in VB

I am creating a fairly simple ping tool which shows in milliseconds how long the server took to respond. If the server does not respond, it shows as it responded in 0ms. I wanted to implement an If statement to write Server failed to respond in the ListBox rather than it replied in 0ms. The only problem with this is I have a chunk of code which need to be run outside the If but continues inside the If and involves using the line of code Next... This seems to cause the If statement to not recognise the End If and the End If to not recognise the If...
Here is my code:
For i As Integer = 0 To numberOfPings - 1
Dim ping As New Ping
Dim pingRe As PingReply = ping.Send(pingTarget)
If pingRe.RoundtripTime = 0 Then
Me.listboxPing.Items.Add("Server failed to respond...")
Else
Me.listboxPing.Items.Add("Response from " & pingTarget & " in " & pingRe.RoundtripTime.ToString() & "ms")
listboxPing.SelectedIndex = listboxPing.Items.Count - 1
listboxPing.SelectedIndex = -1
Application.DoEvents()
Threading.Thread.Sleep(500)
Next
Me.listboxPing.Items.Add("")
End If
Does anyone know of a way I could fix this/get around this issue?
Thanks,
If I were going to write code to ping an address and show the results it would look something like this.
Dim pingThrd As Threading.Thread
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
If pingThrd Is Nothing OrElse pingThrd.ThreadState = Threading.ThreadState.Stopped Then
RichTextBox1.Clear()
pingThrd = New Threading.Thread(AddressOf PingIt)
pingThrd.IsBackground = True
pingThrd.Start("192.168.33.1")
End If
End Sub
Public Sub PingIt(pingTarget As Object)
Dim numberOfPings As Integer = 5
Dim pingT As String = DirectCast(pingTarget, String)
Dim pingTimeOut As Integer = 1000
Const dlyBetweenPing As Integer = 500
Dim dspStr As String
For i As Integer = 0 To numberOfPings - 1
Dim pingit As New Ping
Dim pingRe As PingReply = pingit.Send(pingT, pingTimeOut)
'check if success
If pingRe.Status = IPStatus.Success Then
dspStr = String.Format("Response from: {0} in {1}ms.", pingRe.Address, pingRe.RoundtripTime)
Else
dspStr = String.Format("{0} failed. Status: {1}", pingRe.Address, pingRe.Status)
End If
Me.BeginInvoke(Sub()
RichTextBox1.AppendText(dspStr)
RichTextBox1.AppendText(Environment.NewLine)
End Sub)
Threading.Thread.Sleep(dlyBetweenPing)
Next
End Sub
edit: Same basic code but allow thread to start with different address and count.
Structure PingWhat
Dim addr As String
Dim howmany As Integer
End Structure
Dim pingThrd As Threading.Thread
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
If pingThrd Is Nothing OrElse pingThrd.ThreadState = Threading.ThreadState.Stopped Then
RichTextBox1.Clear()
'setup a thread to do the actual ping'ing
'this allows the UI to function
pingThrd = New Threading.Thread(AddressOf PingIt)
pingThrd.IsBackground = True
'setup address to ping and howmany times to ping it
Dim somePing As New PingWhat With {.addr = "192.168.33.1", .howmany = 3}
'start the thread
pingThrd.Start(somePing)
End If
End Sub
Public Sub PingIt(pingTarget As Object)
Dim pingT As PingWhat = DirectCast(pingTarget, PingWhat)
Dim pingTimeOut As Integer = 1000
Const dlyBetweenPing As Integer = 500
Dim dspStr As String
For i As Integer = 1 To pingT.howmany
Dim pingit As New Ping
Dim pingRe As PingReply = pingit.Send(pingT.addr, pingTimeOut)
'check if success
If pingRe.Status = IPStatus.Success Then
dspStr = String.Format("Response from: {0} in {1} ms.", pingRe.Address, pingRe.RoundtripTime)
Else
dspStr = String.Format("Ping Failed {0}. Status: {1}", pingT.addr, pingRe.Status)
End If
'update the UI
Me.BeginInvoke(Sub()
RichTextBox1.AppendText(dspStr)
RichTextBox1.AppendText(Environment.NewLine)
RichTextBox1.ScrollToCaret()
End Sub)
Threading.Thread.Sleep(dlyBetweenPing)
Next
Me.BeginInvoke(Sub()
RichTextBox1.AppendText("Done")
RichTextBox1.AppendText(Environment.NewLine)
RichTextBox1.ScrollToCaret()
End Sub)
End Sub
Is this what you're after?
For i As Integer = 0 To numberOfPings - 1
Dim ping As New Ping
Dim pingRe As PingReply = ping.Send(pingTarget)
If pingRe.RoundtripTime = 0 Then
Me.listboxPing.Items.Add("Server failed to respond...")
Else
Me.listboxPing.Items.Add("Response from " & pingTarget & " in " & pingRe.RoundtripTime.ToString() & "ms")
listboxPing.SelectedIndex = listboxPing.Items.Count - 1
listboxPing.SelectedIndex = -1
Application.DoEvents()
Threading.Thread.Sleep(500)
add = True
Exit For
End If
Next
If add Then Me.listboxPing.Items.Add("")
The If will change the scope, therefore, you need to use a variable to check whether it went into the Else part.
Of course, you need to close the first If before the Next.
#dbasnett This was the code I using before and it was absolutely perfect for what i needed EXCEPT if a ping failed it would just say (PingTarget) responded in 0ms which is not ideal. Ideally i would like it to say Server failed to respond... . Do you know a way in which this can be achieved by modifying my original code?
Imports System.Net.NetworkInformation
Imports System.Runtime.InteropServices
Public Class PingClient
Private Const EM_SETCUEBANNER As Integer = &H1501
<DllImport("user32.dll", CharSet:=CharSet.Auto)>
Private Shared Function SendMessage(ByVal hWnd As IntPtr, ByVal msg As Integer, ByVal wParam As Integer, <MarshalAs(UnmanagedType.LPWStr)> ByVal lParam As String) As Int32
End Function
Private Sub SetCueText(ByVal control As Control, ByVal text As String)
SendMessage(control.Handle, EM_SETCUEBANNER, 0, text)
End Sub
Private Sub PingClient_Load(sender As Object, e As EventArgs) Handles MyBase.Load
SetCueText(textboxIP, "IP Address/Domain")
SetCueText(textboxPing, "No. Of Pings")
End Sub
Structure PingWhat
Dim addr As String
Dim howmany As Integer
End Structure
Dim pingThrd As Threading.Thread
Public Sub buttonPing_Click(sender As Object, e As EventArgs) Handles buttonPing.Click
If pingThrd Is Nothing OrElse pingThrd.ThreadState = Threading.ThreadState.Stopped Then
Dim pingTarget As String = ""
Dim numberOfPings As Integer = 0
Dim intTimeout As Integer = 2000
If String.IsNullOrEmpty(textboxIP.Text) Then
MsgBox("You must enter an IP Address or Domain.")
Exit Sub
End If
If Not Int32.TryParse(textboxPing.Text, numberOfPings) Then
MsgBox("You must enter a number of how many times the target address will be pinged.")
Exit Sub
End If
If numberOfPings = 0 Then
MsgBox("You must enter a value over 0.")
textboxPing.Clear()
Exit Sub
End If
'setup a thread to do the actual ping'ing
'this allows the UI to function
pingThrd = New Threading.Thread(AddressOf PingIt)
pingThrd.IsBackground = True
'setup address to ping and howmany times to ping it
Dim somePing As New PingWhat With {.addr = pingTarget, .howmany = numberOfPings}
'start the thread
pingThrd.Start(somePing)
End If
Me.listboxPing.Items.Add("")
End Sub
Public Sub PingIt(pingTarget As Object)
Dim pingT As PingWhat = DirectCast(pingTarget, PingWhat)
Dim pingTimeOut As Integer = 1000
Const dlyBetweenPing As Integer = 500
Dim dspStr As String
For i As Integer = 1 To pingT.howmany
Dim pingit As New Ping
Dim pingRe As PingReply = pingit.Send(pingT.addr, pingTimeOut)
'check if success
If pingRe.Status = IPStatus.Success Then
dspStr = String.Format("Response from: {0} in {1} ms.", pingRe.Address, pingRe.RoundtripTime)
Else
dspStr = String.Format("Ping Failed {0}. Status: {1}", pingT.addr, pingRe.Status)
End If
'update the UI
Me.BeginInvoke(Sub()
listboxPing.Items.Add(dspStr)
End Sub)
Threading.Thread.Sleep(dlyBetweenPing)
Next
Me.BeginInvoke(Sub()
listboxPing.Items.Add("Done")
End Sub)
End Sub
Private Sub PingClient_Closing(sender As Object, e As System.ComponentModel.CancelEventArgs) Handles MyBase.Closing
Dim Response As Integer
Response = MsgBox("Are you sure you want to exit the Ping Tool?", 36)
If Response = MsgBoxResult.Yes Then
Else
e.Cancel = True
End If
End Sub
End Class

Making a string from a listbox

I have 2 projects, one which has a highscorelist stored on it, and one which tries to add highscores to that list and retrieve all items on the list. Trying to put items on the list works good, but retrieving the list doesn't work well. Here's the code:
Option Strict On
Option Explicit On
Imports System.Net.Sockets
Imports System.Threading
Public Class Main
Dim server As New TcpListener(45888)
Dim client As New TcpClient
Dim stream As NetworkStream
Dim connected As Boolean
Private Sub cmd_start_Click(sender As Object, e As EventArgs) Handles cmd_start.Click
server.Start()
cmd_start.Enabled = False
cmd_stop.Enabled = True
lbl_status.Text = "Running"
lbl_status.ForeColor = Color.Green
tmr.Start()
End Sub
Private Sub cmd_stop_Click(sender As Object, e As EventArgs) Handles cmd_stop.Click
server.Stop()
cmd_start.Enabled = True
cmd_stop.Enabled = False
lbl_status.Text = "Not running"
lbl_status.ForeColor = Color.Red
tmr.Stop()
End Sub
Private Sub Main_Load(sender As Object, e As EventArgs) Handles MyBase.Load
connected = False
CheckForIllegalCrossThreadCalls = False
End Sub
Dim x As Integer = 0
Private Sub tmr_Tick(sender As Object, e As EventArgs) Handles tmr.Tick
If server.Pending Then
client = server.AcceptTcpClient()
stream = client.GetStream()
tmr.Stop()
read()
Else
tmr.Start()
End If
lbl_mseconds.Text = "Relative time: " & x
x += 1
End Sub
Private Sub SendMessage(message As String)
Dim sendtext() As Byte = System.Text.Encoding.ASCII.GetBytes(message)
stream.Write(sendtext, 0, sendtext.Length)
stream.Flush()
End Sub
Private Sub read()
Dim rec(client.ReceiveBufferSize) As Byte
stream.Read(rec, 0, client.ReceiveBufferSize)
Dim rectext As String = System.Text.Encoding.ASCII.GetString(rec)
If rectext.Contains("#1#") Then
rectext = rectext.Substring(3)
If rectext.Split(CChar("-"))(0).Length = 2 Then rectext = "0" & rectext
If rectext.Split(CChar("-"))(0).Length = 1 Then rectext = "00" & rectext
listbox_highscores.Items.Add(rectext)
ElseIf rectext.Contains("#2#") Then
Dim tosend As String = listbox_highscores.Items(0).ToString
For i = 1 To listbox_highscores.Items.Count - 1
tosend &= "," & listbox_highscores.Items(i).ToString
Next
MsgBox(tosend)
SendMessage(tosend)
End If
tmr.Start()
End Sub
End Class
On the other project I have this:
Dim server As New TcpListener(45888)
Dim client As New TcpClient
Dim stream As NetworkStream
Friend Sub sendHighscore(name As String, score As Integer)
Try
client.Connect("192.168.1.127", 45888)
Catch ex As Exception
Exit Sub
End Try
stream = client.GetStream()
Dim sendtext() As Byte = Encoding.ASCII.GetBytes("#1#" & score & "-" & name)
stream.Write(sendtext, 0, sendtext.Length)
client = New TcpClient
End Sub
Friend Sub getHighscoreList()
ListBox_highscores.Items.Clear()
Try
client.Connect("192.168.1.127", 45888)
Catch ex As Exception
ListBox_highscores.Items.Add("Couldn't connect")
Exit Sub
End Try
stream = client.GetStream()
Dim sendtext() As Byte = Encoding.ASCII.GetBytes("#2#")
stream.Write(sendtext, 0, sendtext.Length)
client = New TcpClient
read()
End Sub
Private Sub read()
Dim rec(client.ReceiveBufferSize) As Byte
stream.Read(rec, 0, client.ReceiveBufferSize)
Dim rectext As String = Encoding.ASCII.GetString(rec)
Label2.Text = rectext
For Each item In rectext.Split(",")
ListBox_highscores.Items.Add(item)
Next
End Sub
Then when I use the sub sendHighscore() with a name and score, everything perfectly works and it shows in the other project on the list, but when I use the sub getHighscoreList() the list on the second project only contains the first item from the first list. Does someone has ideas?
Edit: Original answer removed entirely because it wasn't actually the problem (although it did offer improvements). My answer was nearly identical to this one anyway.
After analyzing this project much more closely, the problem with the For..Next loop not returning the expected results is because the strings are being sent back and forth as byte arrays in buffers much larger than necessary (client.ReceiveBufferSize). The actual "strings" received contain large amounts of non-printable characters (garbage) added to the end to fill the buffer. The quick and dirty solution is to remove all non-printable characters:
rectext = System.Text.RegularExpressions.Regex.Replace(rectext, _
"[^\u0020-\u007F]", String.Empty)
The whole Sub would read like this:
Private Sub read()
Dim rec(client.ReceiveBufferSize) As Byte
stream.Read(rec, 0, client.ReceiveBufferSize)
Dim rectext As String = System.Text.Encoding.ASCII.GetString(rec)
If rectext.Contains("#1#") Then
rectext = rectext.Substring(3)
If rectext.Split(CChar("-"))(0).Length = 2 Then rectext = "0" & rectext
If rectext.Split(CChar("-"))(0).Length = 1 Then rectext = "00" & rectext
rectext = System.Text.RegularExpressions.Regex.Replace(rectext, "[^\u0020-\u007F]", String.Empty)
listbox_highscores.Items.Add(rectext)
ElseIf rectext.Contains("#2#") Then
Dim tosend As String = listbox_highscores.Items(0).ToString
For i As Integer = 1 To (listbox_highscores.Items.Count - 1)
tosend &= "," & listbox_highscores.Items(i).ToString
Next
SendMessage(tosend)
End If
tmr.Start()
End Sub
Try this, your comma's are off as well...
Dim tosend As String = String.Empty
Dim intCount As Integer = 0
For i As Integer = 0 To listbox.Items.Count - 1
If intCount >= 1 Then
tosend &= "," & listbox.Items(i).ToString
Else
tosend &= listbox.Items(i).ToString
intCount += 1
End If
Next
MessageBox.Show(tosend)
Screenshot THAT IT WORKS!

How do I close the tcp client (client.close) with a button?

I have a client server application.
if the client has disconnected the server can detect it automatically and remove it from the connected clients list.
I am going to focus on the server now.
I would like to have a Stop Server button. To stop the Listener and Tcp Client Connections.
I can easily stop the listener, but I am having a hard time trying to figure out how to stop the tcp client ( or issue a Client.Close )
[SERVER]
Public Class Server
Dim ClientList As New Hashtable
Dim Listener As TcpListener
Dim ListenerThread As System.Threading.Thread
Private Sub ButtonStart_Click(sender As Object, e As EventArgs) Handles ButtonStart.Click
ListenerThread = New System.Threading.Thread(AddressOf Listen)
ListenerThread.IsBackground = True
ListenerThread.Start(TextBoxPort.Text)
ButtonStart.Enabled = False
ButtonStop.Enabled = True
ListBox1.Items.Add("[SERVER] Waiting For A Connection...")
End Sub
Sub ClientDisconnected(ByVal Client As ConnectedClient)
ClientList.Remove(Client) 'remove the client from the hashtable
ListBox2.Items.Remove(Client.Name) 'remove it from our listbox
End Sub
Sub Listen(ByVal Port As Integer)
Try
Listener = New TcpListener(IPAddress.Any, Port)
Listener.Start()
Do
Dim Client As New ConnectedClient(Listener.AcceptTcpClient)
AddHandler Client.ReceivedMessage, AddressOf ReceivedMessage
AddHandler Client.ClientDisconnected, AddressOf ClientDisconnected
Loop Until False
Catch
End Try
End Sub
Dim TotalItemCount As String
Sub ReceivedMessage(ByVal Msg As String, ByVal Client As ConnectedClient)
Dim Message() As String = Msg.Split("|")
Select Case Message(0)
Case "CHAT" 'if it's CHAT
ListBox1.Items.Add(Client.Name & " Says: " & " " & Message(1))
Case "SAVETRAN"
ListBox1.Items.Add("Transaction Number: " + Message(1) + vbCrLf + "Customer Number: " + Message(2))
Case "TRANDETAIL"
ListBox1.Items.Add("Barcode: " + Message(1) + vbCrLf + "Quantity: " + Message(2) + vbCrLf + "Price Sold: " + Message(3))
ProgressBar1.Value += 1
Label1.Text = ProgressBar1.Value
If Label1.Text = ProgressBar1.Maximum Then
ProgressBar1.Value = 0
End If
Case "ITEMCOUNT"
ListBox1.Items.Add("SERVER IS EXPECTED TO RECEIVE " + Message(1) + " ITEMS.")
TotalItemCount = Message(1)
ProgressBar1.Maximum = TotalItemCount
Case "LOGIN" 'A client has connected
ClientList.Add(Client, Client.Name)
ListBox2.Items.Add(Client.Name)
End Select
End Sub
Private Sub ButtonStop_Click(sender As Object, e As EventArgs) Handles ButtonStop.Click
Listener.Stop()
ListBox1.Items.Add("Server Stopped")
ButtonStop.Enabled = False
ButtonStart.Enabled = True
End Sub
Private Sub Server_Load(sender As Object, e As EventArgs) Handles MyBase.Load
CheckForIllegalCrossThreadCalls = False
End Sub
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
ListBox1.Items.Clear()
End Sub
End Class
In the Server Application there is a class call ConnectedClient
[Connected Client]
Public Class ConnectedClient
Public Cli As TcpClient
Private UniqueID As String
Public Property Name
Get
Return UniqueID
End Get
Set(ByVal Value)
UniqueID = Value
End Set
End Property
Public Sub New(Client As TcpClient)
Dim r As New Random
Dim x As String = String.Empty
For i = 0 To 7
x &= Chr(r.Next(65, 89))
Next
Me.Name = Client.Client.RemoteEndPoint.ToString().Remove(Client.Client.RemoteEndPoint.ToString().LastIndexOf(":")) & " - " & x
Cli = Client
Cli.GetStream.BeginRead(New Byte() {0}, 0, 0, AddressOf Reading, Nothing)
End Sub
Public Event ReceivedMessage(ByVal Message As String, ByVal Client As ConnectedClient)
Public Event ClientDisconnected(ByVal Client As ConnectedClient)
Sub Reading(ByVal AR As IAsyncResult)
Try
Dim Reader As New StreamReader(Cli.GetStream)
Dim Msg As String = Reader.ReadLine()
RaiseEvent ReceivedMessage(Msg, Me)
Cli.GetStream.BeginRead(New Byte() {0}, 0, 0, AddressOf Reading, Nothing)
Catch ex As Exception
'Try and read again
Try
Dim Reader As New StreamReader(Cli.GetStream)
Dim Msg As String = Reader.ReadLine()
RaiseEvent ReceivedMessage(Msg, Me)
Cli.GetStream.BeginRead(New Byte() {0}, 0, 0, AddressOf Reading, Nothing)
Catch
RaiseEvent ClientDisconnected(Me)
End Try
End Try
End Sub
Sub SendData(ByVal Message As String)
Dim Writer As New StreamWriter(Cli.GetStream)
Writer.WriteLine(Message)
Writer.Flush()
End Sub
End Class
I was trying somehow to link to the connected client class and get the Client.Close, but I cannot
figure it out.

vb.net multi thread chat client and server

i have created a chat server for chatting. there i connect the client pc's that will allow to chat them. In my case, server allow me to connect with that, but i can't able to chat with others make use of my application. Please see my code and correct it. here is my code.
Client side code:
Imports System.Net.Sockets
Imports System.Text
Public Class Form1
Dim clientSocket As New System.Net.Sockets.TcpClient()
Dim serverStream As NetworkStream
Dim readData As String
Dim infiniteCounter As Integer
Private Sub Button1_Click(ByVal sender As System.Object, _
ByVal e As System.EventArgs) Handles Button1.Click
Dim outStream As Byte() = _
System.Text.Encoding.ASCII.GetBytes(TextBox2.Text + "$")
serverStream.Write(outStream, 0, outStream.Length)
serverStream.Flush()
End Sub
Private Sub msg()
If Me.InvokeRequired Then
Me.Invoke(New MethodInvoker(AddressOf msg))
Else
TextBox1.Text = TextBox1.Text + Environment.NewLine + " >> " + readData
End If
End Sub
Private Sub Button2_Click(ByVal sender As System.Object, _
ByVal e As System.EventArgs) Handles Button2.Click
readData = "Conected to Chat Server ..."
msg()
clientSocket.Connect("192.168.1.215", 8888)
'Label1.Text = "Client Socket Program - Server Connected ..."
serverStream = clientSocket.GetStream()
Dim outStream As Byte() = _
System.Text.Encoding.ASCII.GetBytes(TextBox3.Text + "$")
serverStream.Write(outStream, 0, outStream.Length)
serverStream.Flush()
Dim ctThread As Threading.Thread = New Threading.Thread(AddressOf getMessage)
ctThread.Start()
End Sub
Private Sub getMessage()
For infiniteCounter = 1 To 2
infiniteCounter = 1
serverStream = clientSocket.GetStream()
Dim buffSize As Integer
Dim inStream(10024) As Byte
buffSize = clientSocket.ReceiveBufferSize
serverStream.Read(inStream, 0, buffSize)
Dim returndata As String = _
System.Text.Encoding.ASCII.GetString(inStream)
readData = "" + returndata
msg()
Next
End Sub
End Class
server side Code:
Imports System.Net.Sockets
Imports System.Text
Module Module1
Dim clientsList As New Hashtable
Sub Main()
Dim serverSocket As New TcpListener(8888)
Dim clientSocket As TcpClient
Dim infiniteCounter As Integer
Dim counter As Integer
serverSocket.Start()
msg("Chat Server Started ....")
counter = 0
infiniteCounter = 0
For infiniteCounter = 1 To 2
infiniteCounter = 1
counter += 1
clientSocket = serverSocket.AcceptTcpClient()
Dim bytesFrom(10024) As Byte
Dim dataFromClient As String
Dim networkStream As NetworkStream = _
clientSocket.GetStream()
networkStream.Read(bytesFrom, 0, CInt(clientSocket.ReceiveBufferSize))
dataFromClient = System.Text.Encoding.ASCII.GetString(bytesFrom)
dataFromClient = _
dataFromClient.Substring(0, dataFromClient.IndexOf("$"))
clientsList(dataFromClient) = clientSocket
broadcast(dataFromClient + " Joined ", dataFromClient, False)
msg(dataFromClient + " Joined chat room ")
Dim client As New handleClinet
client.startClient(clientSocket, dataFromClient, clientsList)
Next
clientSocket.Close()
serverSocket.Stop()
msg("exit")
Console.ReadLine()
End Sub
Sub msg(ByVal mesg As String)
mesg.Trim()
Console.WriteLine(" >> " + mesg)
End Sub
Private Sub broadcast(ByVal msg As String, _
ByVal uName As String, ByVal flag As Boolean)
Dim Item As DictionaryEntry
For Each Item In clientsList
Dim broadcastSocket As TcpClient
broadcastSocket = CType(Item.Value, TcpClient)
Dim broadcastStream As NetworkStream = _
broadcastSocket.GetStream()
Dim broadcastBytes As [Byte]()
If flag = True Then
broadcastBytes = Encoding.ASCII.GetBytes(uName + " says : " + msg)
Else
broadcastBytes = Encoding.ASCII.GetBytes(msg)
End If
broadcastStream.Write(broadcastBytes, 0, broadcastBytes.Length)
broadcastStream.Flush()
Next
End Sub
Public Class handleClinet
Dim clientSocket As TcpClient
Dim clNo As String
Dim clientsList As Hashtable
Public Sub startClient(ByVal inClientSocket As TcpClient, _
ByVal clineNo As String, ByVal cList As Hashtable)
Me.clientSocket = inClientSocket
Me.clNo = clineNo
Me.clientsList = cList
Dim ctThread As Threading.Thread = New Threading.Thread(AddressOf doChat)
ctThread.Start()
End Sub
Private Sub doChat()
Dim infiniteCounter As Integer
Dim requestCount As Integer
Dim bytesFrom(10024) As Byte
Dim dataFromClient As String
Dim sendBytes As [Byte]()
Dim serverResponse As String
Dim rCount As String
requestCount = 0
For infiniteCounter = 1 To 2
infiniteCounter = 1
Try
requestCount = requestCount + 1
Dim networkStream As NetworkStream = _
clientSocket.GetStream()
networkStream.Read(bytesFrom, 0, CInt(clientSocket.ReceiveBufferSize))
dataFromClient = System.Text.Encoding.ASCII.GetString(bytesFrom)
dataFromClient = _
dataFromClient.Substring(0, dataFromClient.IndexOf("$"))
msg("From client - " + clNo + " : " + dataFromClient)
rCount = Convert.ToString(requestCount)
broadcast(dataFromClient, clNo, True)
Catch ex As Exception
MsgBox(ex.ToString)
End Try
Next
End Sub
End Class
End Module
One, you need to specify your PUBLIC IP address, second, you need to open port 8888 on your router.
Change: clientSocket.Connect("192.168.1.215", 8888) to:
clientSocket.Connect("", 8888)
And make sure to forward port 8888 to your internal LAN IP: 192.168.1.215
Also this is entirely unsecure, I would encrypt and decrypt the strings using triple DES. A little bit of security but at least its security.
Learn a bit about networking bud.