vb.net multi thread chat client and server - vb.net

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.

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:

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

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.

VB.NET: System.ArgumentOutOfRangeException

Im attempting to make a multi-threaded socket program that communicates via TCP. I have followed this tutorial but get the following error.
P.S Im new at network programming
Here is the Stack Trace:
at System.Net.Sockets.NetworkStream.Read(Byte[] buffer, Int32 offset, Int32 size)
at Multi_TCP_Server.Module1.handleClinet.doChat() in \Multi-TCP_Server\Module1.vb:line 57
at System.Threading.ThreadHelper.ThreadStart_Context(Object state)
at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
at System.Threading.ThreadHelper.ThreadStart()
Here is Server code: (Multi-TCP_Server.vb)
Imports System.Net
Imports System.Net.Sockets
Imports System.Text
Module Module1
Sub Main()
Dim LocalAddr As IPAddress = IPAddress.Parse("192.168.1.10")
Dim serverSocket As New TcpListener(LocalAddr, 8888)
Dim clientSocket As TcpClient
Dim counter As Integer
serverSocket.Start()
msg("Server Started")
counter = 0
While (True)
counter += 1
clientSocket = serverSocket.AcceptTcpClient()
msg("Client No:" + Convert.ToString(counter) + " started!")
Dim client As New handleClinet
client.startClient(clientSocket, Convert.ToString(counter))
End While
clientSocket.Close()
serverSocket.Stop()
msg("exit")
Console.ReadLine()
End Sub
Sub msg(ByVal mesg As String)
mesg.Trim()
Console.WriteLine(" >> " + mesg)
End Sub
Public Class handleClinet
Dim clientSocket As TcpClient
Dim clNo As String
Public Sub startClient(ByVal inClientSocket As TcpClient,
ByVal clineNo As String)
Me.clientSocket = inClientSocket
Me.clNo = clineNo
Dim ctThread As Threading.Thread = New Threading.Thread(AddressOf doChat)
ctThread.Start()
End Sub
Private Sub doChat()
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
While (True)
' 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)
serverResponse = "Server to clinet(" + clNo + ") " + rCount
sendBytes = Encoding.ASCII.GetBytes(serverResponse)
networkStream.Write(sendBytes, 0, sendBytes.Length)
networkStream.Flush()
msg(serverResponse)
'Catch ex As Exception
'MsgBox(ex.ToString)
'End Try
End While
End Sub
End Class
End Module
And Here is the Client Code: (Multi-TCP_Client.vb)
Imports System.Net.Sockets
Imports System.Text
Public Class Form1
Dim clientSocket As New System.Net.Sockets.TcpClient()
Dim serverStream As NetworkStream
Private Sub Button1_Click_1(sender As Object, e As EventArgs) Handles Button1.Click
Dim serverStream As NetworkStream = clientSocket.GetStream()
Dim buffSize As Integer
Dim outStream As Byte() = System.Text.Encoding.ASCII.GetBytes("Message from Client")
serverStream.Write(outStream, 32, outStream.Length)
'serverStream.Flush()
Dim inStream(10024) As Byte
buffSize = inStream.Length
serverStream.Read(inStream, 0, buffSize)
Dim returndata As String = System.Text.Encoding.ASCII.GetString(inStream)
msg("Data from Server : " + returndata)
End Sub
Private Sub Form1_Load(ByVal sender As System.Object,
ByVal e As System.EventArgs) Handles MyBase.Load
msg("Client Started")
Try
clientSocket.Connect("192.168.1.10", 8888)
ConnectionStatusLbl.Text = "Server Connected..."
Catch ex As Exception
ConnectionStatusLbl.Text = "Unable to connect."
End Try
End Sub
Sub msg(ByVal mesg As String)
TextBox1.Text = TextBox1.Text + Environment.NewLine + " >> " + mesg
End Sub
End Class
All help and ideas are appreciated.
Thanks :)
EDIT: Here is the Stack Trace from Multi-TCP_Client.vb

Client to client direct chat through server vb.net

Using socket programming, I'm developing a chatting application using vb.net. I have manage to established group chat using a server and multi-client. Now i want to establish a client to client direct chat through server and want to list down all connected clients. If anyone can guide me would be very helpful.
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 counter As Integer
serverSocket.Start()
msg("Chat Server Started ....")
counter = 0
While (True)
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)
End While
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
While (True)
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
End While
End Sub
End Class
End Module

Pass data/parameter to socket thread using VB Net

am running two TCP servers(one in 50010 and other in 10250) in my code both in separate thread
Private Sub frmMainScreen_Load(ByVal eventSender As Object, ByVal eventArgs As EventArgs) Handles MyBase.Load
Dim Local_PortNum As String = Read_GlobalINI_File("TCP-IP CONFIGURATION", "LOCAL_PORT", "TCPIP_Config")
Read_FileLocation()
Dim s As New ClsAutomation_TcpClient
Dim t As New ClsAutomation_TcpClient
trd = New Thread(Sub() s.Main()) ' listens 55000 port
trd1 = New Thread(Sub() t.Main())' listens 10250 port
trd.IsBackground = True
trd.Start()
trd1.IsBackground = True
trd1.Start()
End Sub
here is my tcpserver class
Public Class ClsAutomation_TcpClient
Dim clientsList As New Hashtable
Public WithEvents status_bar1 As System.Windows.Forms.Label
Sub Main()
Dim serverSocket As New TcpListener(IPAddress.Any, 10250)
Dim clientSocket As TcpClient
Dim counter As Integer
Dim clientIPAddress As String
serverSocket.Start()
MsgBox("Chat Server Started ....")
counter = 0
While (True)
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("$"))
Dim ipend As Net.IPEndPoint = clientSocket.Client.RemoteEndPoint
clientIPAddress = ipend.Address.ToString()
clientsList(clientIPAddress) = clientSocket
broadcast(clientIPAddress + " Joined ", dataFromClient, False)
' MsgBox(dataFromClient + " Joined chat room ")
Dim client As New handleClinet
client.startClient(clientSocket, dataFromClient, clientsList)
End While
clientSocket.Close()
serverSocket.Stop()
MsgBox("exit")
End Sub
Sub msg(ByVal mesg As String)
mesg.Trim()
MsgBox(" >> " + 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
End Class
Public Class handleClinet
Public WithEvents status_bar1 As System.Windows.Forms.Label
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 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)
broadcastSocket = Me.clientSocket
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
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
While (True)
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("$"))
'MsgBox("From client - " + clNo + " : " + dataFromClient)
rCount = Convert.ToString(requestCount)
broadcast(dataFromClient, clNo, True)
Catch ex As Exception
MsgBox(ex.ToString)
End Try
End While
End Sub
End Class
Here what i need to do is send data from a btn_click to the (trd) 55000 instance thread...
how would i do it
Your question is quite broad but in simple terms:
You need to create a NetworkStream object.
Assign this using the TcpClient.GetStream method and then call NetworkStream.Write
Something like this (untested) code:
Dim stream as NetworkStream
stream = clientSocket.GetStream
Dim buffer() as byte = System.Text.Encoding.ASCII.GetBytes("hello")
If stream.CanWrite Then stream.Write(buffer, 0, buffer.Length)