Results 1 to 24 of 24

Thread: JpEgy - Working TCP class!!

  1. #1

    Thread Starter
    Banished Cander's Avatar
    Join Date
    Dec 2000
    Location
    Why do you care?
    Posts
    6,913

    JpEgy - Working TCP class!!

    got it working JpEgy. Here it is

    Code:
    ' Thanks goes out to my hommies at www.vbforums.com!
    ' Special Thanks To:
    ' JpEgy for fixing many minor mistakes and being the first tester.
    
    Imports System
    Imports System.Net.Sockets 
    Imports System.Text 
    Imports Microsoft.VisualBasic
    
    Namespace Sockets 
    	' All socket connection types 
    	Namespace TCP 		
    		Public Class TCPConnection
    			' For TCP connections intercepted by the TcpListener 
    			Private tcpConn As TcpClient 
    			Private m_requestID As Guid = Guid.NewGuid 
    			Private objClient As TcpClient 
    			Private arData(1024) As Byte 
    			Private m_ClientIP As String 
    			Private m_State As Short 
    			Private objText As New StringBuilder() 
    			
    			Public Event Connected(ByVal sender As TCPConnection) 
    			Public Event Disconnected(ByVal sender As TCPConnection) 
    			Public Event DataReceived(ByVal sender As TCPConnection, ByVal Data As String, ByVal BytesReceived As Long) 
    			Public Event SockError(ByVal strMessage As String)
    			
    			Public Sub New(ByVal client As TcpClient) 
    				' A new instance of the class started meaning a new connection 
    				objClient = client 
    				RaiseEvent Connected(Me)
    				Console.Writeline("Test")
    				m_State = 1
    				objClient.GetStream.BeginRead(arData, 0, 1024, _ 
    					AddressOf Receive, Nothing) 
    			End Sub
    
    			Public Sub SendData(ByVal Data As String) 
    				' Server sending to client. String Data 
    				m_State = 3
    				SyncLock objClient.GetStream 
    					Dim w As New IO.StreamWriter(objClient.GetStream) 
    					w.Write(Data) 
    					w.Flush() 
    				End SyncLock 
    				m_State = 1
    			End Sub 
    			
    			Private Sub Receive(ByVal ar As IAsyncResult) 
    				' Start the data receiving process 
    				Dim intCount As Integer 
    				Console.Writeline("Received")
    				Try 
    					SyncLock objClient.GetStream 
    						intCount = objClient.GetStream.EndRead(ar) 
    					End SyncLock 
    					If intCount < 1 Then 
    						RaiseEvent Disconnected(Me)
    						m_State = 0
    						Exit Sub 
    					End If 
    
    					BuildString(arData, 0, intCount) 
    					SyncLock objClient.GetStream 
    						objClient.GetStream.BeginRead(arData, 0, 1024, AddressOf Receive, Nothing) 
    					End SyncLock 
    				Catch e As Exception
    					RaiseEvent SockError(e.Message.ToString)
    					RaiseEvent Disconnected(Me) 
    					m_State = 0
    				End Try 
    			End Sub 
    
    			Private Sub BuildString(ByVal Bytes() As Byte, ByVal offset As Integer, ByVal count As Integer) 
    				Dim intIndex As Integer 
    				Dim txt As String
    				Console.Writeline("BuildString")
    				m_State = 2
    				
    				objText = New StringBuilder() 
    				For intIndex = offset To offset + count - 1 
    					txt = ChrW(Bytes(intIndex))
    					objText.Append(txt)
    				Next 
    				RaiseEvent DataReceived(Me, objText.ToString, objText.Length)
    				m_State = 1
    			End Sub 
    
    			Public ReadOnly Property requestID() As String 
    				' A connections requestID to identify it. 
    				Get 
    					Return m_requestID.ToString 
    				End Get 
    			End Property 
    
    			Public ReadOnly Property ClientIP() As String 
    				' The ip address of the connected client 
    				Get
    					Return m_ClientIP 
    				End Get 
    			End Property 
    
    			Public ReadOnly Property State() As Short 
    				' The ip address of the connected client 
    				' Possible values:
    				' 0 - Disconnected
    				' 1 - Connected And Ready
    				' 2 - Receiving
    				' 3 - Sending
    				' 4 - Connecting
    				Get 
    					Return m_State 
    				End Get 
    			End Property
    			
    			Public Sub Connect(ByVal strDomain As String, ByVal intPort As Integer)
    			        m_State = 4
    				Try
    			            	objClient = New TcpClient(strDomain, intPort)
    			            	RaiseEvent Connected(Me)
    				    	m_State = 1
    			            	objClient.ReceiveBufferSize = 1024
    			            	objClient.NoDelay = True
    			        Catch e As Exception
    			            	RaiseEvent SockError(e.Message.ToString)
    				    	m_State = 0
    			        End Try
        			End Sub
    		End Class 
    	End Namespace 
    End Namespace
    Stack Overflow
    See the features of Visual Studio 2010 and C# 4.0: The 10-4 show on Channel9

  2. #2

    Thread Starter
    Banished Cander's Avatar
    Join Date
    Dec 2000
    Location
    Why do you care?
    Posts
    6,913

    Update

    Sending was broken..it is fixed now..

    Code:
    ' Thanks goes out to my hommies at www.vbforums.com!
    ' Special Thanks To:
    ' JpEgy for fixing many minor mistakes and being the first tester.
    ' This file written with TextPad... Who needs Visual Studio?
    
    Option Explicit 
    
    Imports System
    Imports System.Net.Sockets 
    Imports System.Text 
    Imports Microsoft.VisualBasic
    
    Namespace Sockets 
    	' All socket connection types 
    	Namespace TCP 		
    		Public Class TCPConnection
    			' For TCP connections intercepted by the TcpListener 
    			Private tcpConn As TcpClient 
    			Private m_requestID As Guid = Guid.NewGuid 
    			Private objClient As TcpClient 
    			Private arData(1024) As Byte 
    			Private m_ClientIP As String 
    			Private m_State As Short 
    			Private objText As New StringBuilder() 
    			
    			Public Event Connected(ByVal sender As TCPConnection) 
    			Public Event Disconnected(ByVal sender As TCPConnection) 
    			Public Event DataReceived(ByVal sender As TCPConnection, ByVal Data As String, ByVal BytesReceived As Long) 
    			Public Event SockError(ByVal strMessage As String)
    			
    			Public Sub New(ByVal client As TcpClient) 
    				' A new instance of the class started meaning a new connection 
    				objClient = client
    				'RaiseEvent Connected(Me)
    				'Console.Writeline("Test")
    				m_State = 1
    				objClient.GetStream.BeginRead(arData, 0, 1024, _ 
    					AddressOf Receive, Nothing) 
    			End Sub
    
    			Public Sub SendData(ByVal Data As String) 
    				' Server sending to client. String Data 
    				m_State = 3
               			objClient.Send(Encoding.ASCII.GetBytes(Data))
    				m_State = 1
    			End Sub 
    			
    			Private Sub Receive(ByVal ar As IAsyncResult) 
    				' Start the data receiving process 
    				Dim intCount As Integer 
    				Console.Writeline("Received")
    				Try 
    					SyncLock objClient.GetStream 
    						intCount = objClient.GetStream.EndRead(ar) 
    					End SyncLock 
    					If intCount < 1 Then 
    						RaiseEvent Disconnected(Me)
    						m_State = 0
    						Exit Sub 
    					End If 
    
    					BuildString(arData, 0, intCount) 
    					SyncLock objClient.GetStream 
    						objClient.GetStream.BeginRead(arData, 0, 1024, AddressOf Receive, Nothing) 
    					End SyncLock 
    				Catch e As Exception
    					RaiseEvent SockError(e.Message.ToString)
    					RaiseEvent Disconnected(Me) 
    					m_State = 0
    				End Try 
    			End Sub 
    
    			Private Sub BuildString(ByVal Bytes() As Byte, ByVal offset As Integer, ByVal count As Integer) 
    				Dim intIndex As Integer 
    				Dim txt As String
    				Console.Writeline("BuildString")
    				m_State = 2
    				
    				objText = New StringBuilder() 
    				For intIndex = offset To offset + count - 1 
    					txt = ChrW(Bytes(intIndex))
    					objText.Append(txt)
    				Next 
    				RaiseEvent DataReceived(Me, objText.ToString, objText.Length)
    				m_State = 1
    			End Sub 
    
    			Public ReadOnly Property requestID() As String 
    				' A connections requestID to identify it.
    				' This property returns a Guid. Use this to identify a specific
    				' client when using as as multi-connection server. You can
    				' store the class reference into a collection or hashtable
    				' and use the requestID as the unique key.
    				Get 
    					Return m_requestID.ToString 
    				End Get 
    			End Property 
    
    			Public ReadOnly Property ClientIP() As String 
    				' The ip address of the connected client 
    				Get
    					Return m_ClientIP 
    				End Get 
    			End Property 
    
    			Public ReadOnly Property State() As Short 
    				' The ip address of the connected client 
    				' Possible values:
    				' 0 - Disconnected
    				' 1 - Connected And Ready
    				' 2 - Receiving
    				' 3 - Sending
    				' 4 - Connecting
    				Get 
    					Return m_State 
    				End Get 
    			End Property
    			
    			Public Sub Connect(ByVal strDomain As String, ByVal intPort As Integer)
    			        m_State = 4
    				Try
    			            	objClient = New TcpClient(strDomain, intPort)
    			            	RaiseEvent Connected(Me)
    				    	m_State = 1
    			            	objClient.ReceiveBufferSize = 1024
    			            	objClient.NoDelay = True
    			        Catch e As Exception
    			            	RaiseEvent SockError(e.Message.ToString)
    				    	m_State = 0
    			        End Try
        			End Sub
    		End Class 
    	End Namespace 
    End Namespace
    Stack Overflow
    See the features of Visual Studio 2010 and C# 4.0: The 10-4 show on Channel9

  3. #3
    Frenzied Member DevGrp's Avatar
    Join Date
    Nov 2001
    Location
    Charlotte, NC
    Posts
    1,256
    Hey Cander, could you comment this code.

    I have never done any network programming and would really like to know what is going on in this code.

    Never too late to learn something new.

    Thanks
    Dont gain the world and lose your soul

  4. #4

    Thread Starter
    Banished Cander's Avatar
    Join Date
    Dec 2000
    Location
    Why do you care?
    Posts
    6,913
    Sure thing, I will work on it this afternoon to add more comments. I
    Stack Overflow
    See the features of Visual Studio 2010 and C# 4.0: The 10-4 show on Channel9

  5. #5

    Thread Starter
    Banished Cander's Avatar
    Join Date
    Dec 2000
    Location
    Why do you care?
    Posts
    6,913
    ok ive added some comments that i hope will explain some of it better

    VB Code:
    1. ' Thanks goes out to my hommies at [url]www.vbforums.com[/url]!
    2. ' Special Thanks To:
    3. ' JpEgy for fixing many minor mistakes and being the first tester.
    4. ' This file written with TextPad... Who needs Visual Studio?
    5.  
    6. Option Explicit
    7.  
    8. Imports System
    9. Imports System.Net.Sockets
    10. Imports System.Text
    11. Imports Microsoft.VisualBasic
    12.  
    13. Namespace Sockets
    14.     ' All socket connection types
    15.     Namespace TCP      
    16.         Public Class TCPConnection
    17.             ' For TCP connections intercepted by the TcpListener
    18.             Private tcpConn As TcpClient
    19.             Private m_requestID As Guid = Guid.NewGuid
    20.             Private objClient As TcpClient
    21.             Private arData(1024) As Byte
    22.             Private m_ClientIP As String
    23.             Private m_State As Short
    24.             Private objText As New StringBuilder()
    25.            
    26.             Public Event Connected(ByVal sender As TCPConnection)
    27.             Public Event Disconnected(ByVal sender As TCPConnection)
    28.             Public Event DataReceived(ByVal sender As TCPConnection, ByVal Data As String, ByVal BytesReceived As Long)
    29.             Public Event SockError(ByVal strMessage As String)
    30.            
    31.             Public Sub New(ByVal client As TcpClient)
    32.                 ' A new instance of the class started meaning a new connection
    33.                 ' New is a constructor that it called when New is used with creating
    34.                 ' A class instance
    35.                 objClient = client
    36.                 'RaiseEvent Connected(Me)
    37.                 'Console.Writeline("Test")
    38.                 m_State = 1
    39.                 ' Have the TcpClient object listen in the background for incoming
    40.                 ' data and call the Receive sub whenit does.
    41.                 objClient.GetStream.BeginRead(arData, 0, 1024, _
    42.                     AddressOf Receive, Nothing)
    43.             End Sub
    44.  
    45.             Public Sub SendData(ByVal Data As String)
    46.                 ' Server sending to client. String Data
    47.                 m_State = 3
    48.                     ' Send the string of Data to the client
    49.                     objClient.Send(Encoding.ASCII.GetBytes(Data))
    50.                 m_State = 1
    51.             End Sub
    52.            
    53.             Private Sub Receive(ByVal ar As IAsyncResult)
    54.                 ' Start the data receiving process
    55.                 Dim intCount As Integer
    56.                 Console.Writeline("Received")
    57.                 Try
    58.                     ' check for an error while receiving data
    59.                     SyncLock objClient.GetStream
    60.                         intCount = objClient.GetStream.EndRead(ar)
    61.                     End SyncLock
    62.                     If intCount < 1 Then
    63.                         RaiseEvent Disconnected(Me)
    64.                         m_State = 0
    65.                         Exit Sub
    66.                     End If
    67.                     ' Create a string from the byte array of data received by the
    68.                     ' objclient.GetStream
    69.                     BuildString(arData, 0, intCount)
    70.                     ' Restart the background listening for incoming data
    71.                     SyncLock objClient.GetStream
    72.                         objClient.GetStream.BeginRead(arData, 0, 1024, AddressOf Receive, Nothing)
    73.                     End SyncLock
    74.                 Catch e As Exception
    75.                     RaiseEvent SockError(e.Message.ToString)
    76.                     RaiseEvent Disconnected(Me)
    77.                     m_State = 0
    78.                 End Try
    79.             End Sub
    80.  
    81.             Private Sub BuildString(ByVal Bytes() As Byte, ByVal offset As Integer, ByVal count As Integer)
    82.                 Dim intIndex As Integer
    83.                 Dim txt As String
    84.                 Console.Writeline("BuildString")
    85.                 m_State = 2
    86.                
    87.                 objText = New StringBuilder()
    88.                 ' Loop through the Byte array byte by byte and turn it into a unicode
    89.                 ' string
    90.                 For intIndex = offset To offset + count - 1
    91.                     txt = ChrW(Bytes(intIndex))
    92.                     objText.Append(txt)
    93.                 Next
    94.                 RaiseEvent DataReceived(Me, objText.ToString, objText.Length)
    95.                 m_State = 1
    96.             End Sub
    97.  
    98.             Public ReadOnly Property requestID() As String
    99.                 ' A connections requestID to identify it.
    100.                 ' This property returns a Guid. Use this to identify a specific
    101.                 ' client when using as as multi-connection server. You can
    102.                 ' store the class reference into a collection or hashtable
    103.                 ' and use the requestID as the unique key.
    104.                 Get
    105.                     Return m_requestID.ToString
    106.                 End Get
    107.             End Property
    108.  
    109.             Public ReadOnly Property ClientIP() As String
    110.                 ' The ip address of the connected client
    111.                 Get
    112.                     Return m_ClientIP
    113.                 End Get
    114.             End Property
    115.  
    116.             Public ReadOnly Property State() As Short
    117.                 ' The ip address of the connected client
    118.                 ' Possible values:
    119.                 ' 0 - Disconnected
    120.                 ' 1 - Connected And Ready
    121.                 ' 2 - Receiving
    122.                 ' 3 - Sending
    123.                 ' 4 - Connecting
    124.                 Get
    125.                     Return m_State
    126.                 End Get
    127.             End Property
    128.            
    129.             Public Sub Connect(ByVal strDomain As String, ByVal intPort As Integer)
    130.                     m_State = 4
    131.                 Try
    132.                     ' Start a new client passing the ip and port
    133.                             objClient = New TcpClient(strDomain, intPort)
    134.                             RaiseEvent Connected(Me)
    135.                         m_State = 1
    136.                         ' Max data buffer size
    137.                             objClient.ReceiveBufferSize = 1024
    138.                             objClient.NoDelay = True
    139.                     Catch e As Exception
    140.                             RaiseEvent SockError(e.Message.ToString)
    141.                         m_State = 0
    142.                     End Try
    143.                 End Sub
    144.         End Class
    145.     End Namespace
    146. End Namespace
    Stack Overflow
    See the features of Visual Studio 2010 and C# 4.0: The 10-4 show on Channel9

  6. #6
    Frenzied Member DevGrp's Avatar
    Join Date
    Nov 2001
    Location
    Charlotte, NC
    Posts
    1,256
    Thanks , I'll test this out later when I get home today.
    Dont gain the world and lose your soul

  7. #7
    Junior Member
    Join Date
    Mar 2002
    Location
    trinsic
    Posts
    21

    only error

    objClient.Send(Encoding.ASCII.GetBytes(Data))

    is at objclient.send

  8. #8

    Thread Starter
    Banished Cander's Avatar
    Join Date
    Dec 2000
    Location
    Why do you care?
    Posts
    6,913
    this is starnge...eveyone is getting this compile error except me.


    i gotta figure out what is wrong..
    Stack Overflow
    See the features of Visual Studio 2010 and C# 4.0: The 10-4 show on Channel9

  9. #9

    Thread Starter
    Banished Cander's Avatar
    Join Date
    Dec 2000
    Location
    Why do you care?
    Posts
    6,913
    ARRGHH! Then it stopped working on my machine..That makes no sense as it was working as is on my machine...Oh well...anyway..I rewrote the sending again. It is working again..hope it stays that way..

    Code:
    ' Thanks goes out to my hommies at www.vbforums.com!
    ' Special Thanks To:
    ' JpEgy for fixing many minor mistakes and being the first tester.
    ' This file written with TextPad... Who needs Visual Studio?
    
    Option Explicit 
    
    Imports System
    Imports System.Net
    Imports System.Net.Sockets 
    Imports System.Text 
    Imports System.IO
    Imports Microsoft.VisualBasic
    
    Namespace Sockets 
    	' All socket connection types 
    	Namespace TCP 		
    		Public Class TCPConnection
    			' For TCP connections intercepted by the TcpListener 
    			Private tcpConn As TcpClient 
    			Private m_requestID As Guid = Guid.NewGuid 
    			Private objClient As TcpClient 
    			Private arData(1024) As Byte 
    			Private m_ClientIP As String 
    			Private m_State As Short 
    			Private objText As New StringBuilder() 
    			Private objWriter As BinaryWriter
    			
    			Public Event Connected(ByVal sender As TCPConnection) 
    			Public Event Disconnected(ByVal sender As TCPConnection) 
    			Public Event DataReceived(ByVal sender As TCPConnection, ByVal Data As String, ByVal BytesReceived As Long) 
    			Public Event SockError(ByVal strMessage As String)
    			
    			Public Sub New(ByVal client As TcpClient) 
    				' A new instance of the class started meaning a new connection 
    				' New is a constructor that it called when New is used with creating
    				' A class instance
    				objClient = client
    				'RaiseEvent Connected(Me)
    				'Console.Writeline("Test")
    				m_State = 1
    				' Have the TcpClient object listen in the background for incoming 
    				' data and call the Receive sub whenit does.
    				objClient.GetStream.BeginRead(arData, 0, 1024, _ 
    					AddressOf Receive, Nothing) 
    			End Sub
    
    			Public Sub SendData(ByVal Data As String) 
    				' Server sending to client. String Data 
    				m_State = 3
               			' Send the string of Data to the client
               			'objClient.SendDataToClient(Encoding.ASCII.GetBytes(Data))
               			'Dim sendbyteData() As Byte = byteData
    				objWriter = New BinaryWriter(objClient.GetStream)
    				Try
    					objWriter.Write(Encoding.ASCII.GetBytes(Data), 0, Data.Length)
                				objWriter.Flush()
                			Catch e As Exception
                				Console.Writeline(e.Message.ToString)
                			End Try
    				m_State = 1
    			End Sub 
    			
    			Private Sub Receive(ByVal ar As IAsyncResult) 
    				' Start the data receiving process 
    				Dim intCount As Integer 
    				Console.Writeline("Received")
    				Try 
    					' check for an error while receiving data
    					SyncLock objClient.GetStream 
    						intCount = objClient.GetStream.EndRead(ar) 
    					End SyncLock 
    					If intCount < 1 Then 
    						RaiseEvent Disconnected(Me)
    						m_State = 0
    						Exit Sub 
    					End If 
    					' Create a string from the byte array of data received by the
    					' objclient.GetStream
    					BuildString(arData, 0, intCount) 
    					' Restart the background listening for incoming data
    					SyncLock objClient.GetStream 
    						objClient.GetStream.BeginRead(arData, 0, 1024, AddressOf Receive, Nothing) 
    					End SyncLock 
    				Catch e As Exception
    					RaiseEvent SockError(e.Message.ToString)
    					RaiseEvent Disconnected(Me) 
    					m_State = 0
    				End Try 
    			End Sub 
    
    			Private Sub BuildString(ByVal Bytes() As Byte, ByVal offset As Integer, ByVal count As Integer) 
    				Dim intIndex As Integer 
    				Dim txt As String
    				Console.Writeline("BuildString")
    				m_State = 2
    				
    				objText = New StringBuilder() 
    				' Loop through the Byte array byte by byte and turn it into a unicode
    				' string
    				For intIndex = offset To offset + count - 1 
    					txt = ChrW(Bytes(intIndex))
    					objText.Append(txt)
    				Next 
    				RaiseEvent DataReceived(Me, objText.ToString, objText.Length)
    				m_State = 1
    			End Sub 
    
    			Public ReadOnly Property requestID() As String 
    				' A connections requestID to identify it.
    				' This property returns a Guid. Use this to identify a specific
    				' client when using as as multi-connection server. You can
    				' store the class reference into a collection or hashtable
    				' and use the requestID as the unique key.
    				Get 
    					Return m_requestID.ToString 
    				End Get 
    			End Property 
    
    			Public ReadOnly Property ClientIP() As String 
    				' The ip address of the connected client 
    				Get
    					Return m_ClientIP 
    				End Get 
    			End Property 
    
    			Public ReadOnly Property State() As Short 
    				' The ip address of the connected client 
    				' Possible values:
    				' 0 - Disconnected
    				' 1 - Connected And Ready
    				' 2 - Receiving
    				' 3 - Sending
    				' 4 - Connecting
    				Get 
    					Return m_State 
    				End Get 
    			End Property
    			
    			Public Sub Connect(ByVal strDomain As String, ByVal intPort As Integer)
    			        m_State = 4
    				Try
    					' Start a new client passing the ip and port
    			            	objClient = New TcpClient(strDomain, intPort)
    			            	RaiseEvent Connected(Me)
    				    	m_State = 1
    				    	' Max data buffer size
    			            	objClient.ReceiveBufferSize = 1024
    			            	objClient.NoDelay = True
    			        Catch e As Exception
    			            	RaiseEvent SockError(e.Message.ToString)
    				    	m_State = 0
    			        End Try
        			End Sub
    		End Class 
    	End Namespace 
    End Namespace
    Stack Overflow
    See the features of Visual Studio 2010 and C# 4.0: The 10-4 show on Channel9

  10. #10
    Junior Member
    Join Date
    Mar 2002
    Location
    trinsic
    Posts
    21

    Question question

    goin thru all this.. but where does it specificy what port to listen on?
    thanks

  11. #11
    Frenzied Member Jop's Avatar
    Join Date
    Mar 2000
    Location
    Amsterdam, the Netherlands
    Posts
    1,986
    VB Code:
    1. Public Sub Connect(ByVal strDomain As String, ByVal intPort As Integer)

    so it would be connect("mydomain.com", MyPortNumber)
    Jop - validweb.nl

    Alcohol doesn't solve any problems, but then again, neither does milk.

  12. #12
    Junior Member
    Join Date
    Mar 2002
    Location
    trinsic
    Posts
    21

    great

    hm.. ok you can connect with that.. but bare with me for a second... have never messed with tcp/ip..(btw.. what's a good book to read to learn it?) i can connect.. but how do i make a server listen on a certain port for incoming connections...


    karthic

  13. #13

    Thread Starter
    Banished Cander's Avatar
    Join Date
    Dec 2000
    Location
    Why do you care?
    Posts
    6,913
    sorry guess i should include the server usage example. This class does not do the listenting. You need to add a TcPListener class which is where the port is specified..here is a sample app showing how to listen for multiple connections on port 2500, store the clients into a hashtable(aka collection) and send data to all clients connected

    Code:
    Imports System
    Imports System.Net
    Imports System.Net.Sockets
    Imports Sockets.TCP
    Imports System.Threading
    Imports System.Collections
    
    Module App1
    
    Private mobjListener As TcpListener
    Private WithEvents x As TCPConnection
    Private thdListen As Thread
    Private colClients As New Hashtable()
    
    Sub Main()
    	Console.WriteLine("Server Started")
            thdListen = New Thread(AddressOf DoListen)
        	thdListen.Start()
    End Sub
    
    Private Sub DoListen()
    	Try
    		' Start the listening Socket on port 2500
    		mobjListener = New TcpListener(2500)
    		mobjListener.Start()
          		Do
    			x = New TCPConnection(mobjListener.AcceptTcpClient)
    			AddHandler x.DataReceived, AddressOf OnDataReceived
    			Console.Writeline("New Connection Received")
    			AddHandler x.Connected, AddressOf Connection
    			' Add class reference to a hashtable for later reference. Make the
    			' requestID the unique key.
    			colClients.Add(x.requestID, x)
          		Loop Until False
    	Catch
    	End Try
    End Sub
    
    Private Sub OnDataReceived(ByVal sender As TCPConnection, ByVal Data As String, ByVal Bytes As Long)
    	Console.Writeline("in: " & Data)
       	Console.Writeline("id: " & sender.requestID)
       	Console.Writeline("bytes: " & Bytes)
       	Dim y As DictionaryEntry
    	Dim a As TCPConnection
    	For Each y In colClients
    		' Set a to the value of the current class from the hashtable
    		a = y.Value
    		Console.Writeline(a.requestID)
    		a.SendData(Data)
    	
    	Next y
    	
    End Sub
    
    Sub Connection(ByVal sender As TCPConnection)
    	Console.WriteLine("Connection")
    End Sub
    
    End Module
    Stack Overflow
    See the features of Visual Studio 2010 and C# 4.0: The 10-4 show on Channel9

  14. #14
    Junior Member
    Join Date
    Mar 2002
    Location
    trinsic
    Posts
    21

    excuse me while i',m still learning

    Code:
            Dim asdf As Sockets.TCP.TCPConnection
            asdf.Connect("mydomain.com", 23)
    compiles with the error
    Code:
    Additional information: Object reference not set to an instance of an object.
    what does that error mean?
    hmm
    thanks
    karthic

  15. #15
    Junior Member
    Join Date
    Mar 2002
    Location
    trinsic
    Posts
    21

    still cant figure out

    how to run the sub's in that namespace.. just cant do it..
    hmmm
    gezz
    help?

  16. #16
    Frenzied Member Jop's Avatar
    Join Date
    Mar 2000
    Location
    Amsterdam, the Netherlands
    Posts
    1,986
    Not sure in this case... but you can try:
    VB Code:
    1. Dim asdf As [b]New[/b] Sockets.TCP.TCPConnection

    Good luck
    Jop - validweb.nl

    Alcohol doesn't solve any problems, but then again, neither does milk.

  17. #17
    Junior Member
    Join Date
    Mar 2002
    Location
    trinsic
    Posts
    21

    ok.. last question on this topic

    i promise.. sure.. sure..

    how do i send binary data, like mp3 files from this to a client.. for it to recieve and store to a file... i just cant figgure that out..
    thanks
    karthic

  18. #18

    Thread Starter
    Banished Cander's Avatar
    Join Date
    Dec 2000
    Location
    Why do you care?
    Posts
    6,913
    Use the Disconnected event.
    Stack Overflow
    See the features of Visual Studio 2010 and C# 4.0: The 10-4 show on Channel9

  19. #19

    Thread Starter
    Banished Cander's Avatar
    Join Date
    Dec 2000
    Location
    Why do you care?
    Posts
    6,913
    Did you add the class to the project?
    Stack Overflow
    See the features of Visual Studio 2010 and C# 4.0: The 10-4 show on Channel9

  20. #20
    Your Ad Here! Edneeis's Avatar
    Join Date
    Feb 2000
    Location
    Moreno Valley, CA (SoCal)
    Posts
    7,339
    Can you serialize objects to the network stream? I am using basically this class but instead of writing the string to the stream with the streamwriter I am serializing a Message object but I keep getting out of memory errors.

  21. #21
    Member
    Join Date
    May 2001
    Location
    Adelaide, Australia
    Posts
    51

    Any idea what'd be causing this?

    Was working great, then I tried to get it handling each connection in a separate thread (I don't think that's what it's doing at the moment, anyway), and Bad Things started happening. Specifically:
    Code:
    Unable to read data from the transport connection.
    
    at System.Net.Sockets.NetworkStream.EndRead(IAsyncResult asyncResult)
    at TCPConnection.Receive(IAsyncResult ar) in TCPConnection.vb:line 69
    My DoListen() function (based on the function used in the original thread):
    VB Code:
    1. Private Sub DoListen()
    2.         mobjListener = New Net.Sockets.TcpListener(27753)
    3.  
    4.         mobjListener.Start()
    5.         Do
    6.             Dim x As New TCPConnection(mobjListener.AcceptTcpClient)
    7.             Dim myThread As Threading.Thread = New Threading.Thread(AddressOf x.Go)
    8.             AddHandler x.DataReceived, AddressOf OnDataReceived
    9.             AddHandler x.OnDisconnect, AddressOf myThread.Abort
    10.             myThread.Start()
    11.         Loop Until False
    12.     End Sub

    And to get that working, I split the New() function into the following:
    VB Code:
    1. Public Sub New(ByVal client As TcpClient)
    2.         ' A new instance of the class started meaning a new connection
    3.         ' New is a constructor that it called when New is used with creating
    4.         ' A class instance
    5.         objClient = client
    6.     End Sub
    7.  
    8.     Public Sub Go()
    9.         RaiseEvent Connected(Me)
    10.         m_State = 1
    11.         ' Have the TcpClient object listen in the background for incoming
    12.         ' data and call the Receive sub whenit does.
    13.         objClient.GetStream.BeginRead(arData, 0, 1024, AddressOf Receive, Nothing)
    14.     End Sub
    Matthew Draper
    [email protected]

    "Genius may have its limitations, but stupidity is not thus handicapped." - Elbert Hubbard

    "I like long walks, especially when they are taken by people who annoy me." - Noel Coward

  22. #22
    Addicted Member
    Join Date
    Sep 2001
    Posts
    148
    Could you please post an example on client usage (threaded)?

    Thanks.

  23. #23
    Member
    Join Date
    Mar 2003
    Posts
    32
    Can someone re code the server part? I can't seem to get it to work.

  24. #24
    New Member
    Join Date
    Jan 2006
    Posts
    15

    Re: JpEgy - Working TCP class!!

    Hi all .

    I need a full sample for tranasfer file between 2 pc on the network with VB.NET2005 .

    does anyone have a client/server application to get me .?

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  



Click Here to Expand Forum to Full Width