0
Reply

Convert Tcp class into multi-thread

jimmypearly

jimmypearly

Aug 24 2004 5:35 PM
1.7k
How do i convert the following into a fully multithreaded tcp server and remove the two addhandler(linerecieved,ondisconnected), i just know how to remove the addhandler and make it into a separate thread. any help would be appreciated. thanks jim [UI form] Option Strict On Imports System.Threading Imports System.Net.Sockets Imports System.Net Private myThread as thread private mysocket as Tcplistener Private Sub clsServer_load(...) mythread = New threading.thread(addressof Dolisten) mythread.start() end sub Pirvate dolisten() dim localaddr = system.net.ipaddress try mysocket = new Tcplistener(localaddr,1234) mysocket.start() do dim x as New clsClient(mysocket.AcceptTcpClient) AddHandler x.Disconnected, AddressOf onDisconnected AddHandler x.myReceived, AddressOf LineReceived mcolClients.Add(x.ID, x) Loop Until False catch end try end sub Public Sub LineReceived(ByVal sender As clsClient, ByVal strString As String) 'process recive data here end sub [clsClient.vb] Option Strict On Imports System.Net.Sockets Imports System.Text 'client class to handle the new client connected to the server Public Class clsClient Public Event Disconnected(ByVal sender As clsClient) Public Event LineReceived(ByVal sender As clsClient, ByVal Data As String) Private mgID As Guid = Guid.NewGuid Const BUFFER_SIZE As Integer = 512 Private mobjClient As TcpClient Private marData(BUFFER_SIZE) As Byte Private mobjText As New StringBuilder() Public ReadOnly Property ID() As String Get Return mgID.ToString End Get End Property Public Sub New(ByVal client As TcpClient) mobjClient = client mobjClient.GetStream.BeginRead(marData, 0, BUFFER_SIZE, AddressOf DoStreamReceive, Nothing) End Sub Private Sub DoStreamReceive(ByVal ar As IAsyncResult) Dim intCount As Integer Dim clientdata As String = Encoding.ASCII.GetString(marData) Try SyncLock mobjClient.GetStream intCount = mobjClient.GetStream.EndRead(ar) End SyncLock If intCount < 1 Then RaiseEvent Disconnected(Me) Exit Sub End If RaiseEvent LineReceived(Me, clientdata) SyncLock mobjClient.GetStream mobjClient.GetStream.BeginRead(marData, 0, BUFFER_SIZE, AddressOf DoStreamReceive, Nothing) End SyncLock Catch ex As Exception RaiseEvent Disconnected(Me) End Try End Sub Public Sub Send(ByVal Data As String) SyncLock mobjClient.GetStream Dim w As New IO.StreamWriter(mobjClient.GetStream) w.Write(Data) w.Flush() End SyncLock End Sub End Class