Send message to all multithreaded clients help.
Given the code, ss there a way to propagate messages send from any of the multithreaded chat client to all the other chat client:
Thanks!
First the main will call startClient:
Code:
Public Sub startClient(ByVal inClientSocket As TcpClient, _
ByVal clineNo As String)
'Dim clientCounter As Integer
Dim arr_inClientSocket(clientCounter) As TcpClient
arr_inClientSocket(clientCounter) = inClientSocket
clientCounter += 1
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 ' Return message to client
sendBytes = Encoding.ASCII.GetBytes(serverResponse)
'I thought I could do something here tosend the message to all chat clients but ain't got an idea how.
networkStream.Write(sendBytes, 0, sendBytes.Length)
networkStream.Flush()
msg(serverResponse)
Catch ex As Exception
MsgBox(ex.ToString)
End Try
End While
End Sub
Re: Send message to all multithreaded clients help.
I would recommend against creating a new Thread for every client. You can follow the CodeBank link in my signature and check out my Asynchronous TCP post for a better way to do it. You only manage a single thread and make asynchronous calls, letting the system worry about the details. To broadcast a message to all clients you can then use the ThreadPool, e.g.
vb.net Code:
Private Sub BroadcastMessage(ByVal originatingClient As TcpClient, ByVal message As String)
For Each client As TcpClient In Me.allClients
If client IsNot originatingClient Then
ThreadPool.QueueUserWorkItem(AddressOf SendMessage, New ClientMessage(client, message))
End If
Next
End Sub
You'd have to define the ClientMessage type and the SendMessage method appropriately.