Sockets and multiple connections example?

tical

Newcomer
Joined
Oct 1, 2003
Messages
2
Hey guys,

I'm pretty new to VB.net and I like it so far but one thing that's sort of over my head are the sockets.

I've found a couple irc tutorials on sockets but I just can't seem to grasp how they work.

Does anyone here know of some sample code or an example on how to create a multiple-client socket application?

I'm stumped on how to wait for incoming data for a dynamic number of connections (i.e. winsock dataarival(index as integer))

I'm actually stumped on all of it. What are the best methods to go about setting up a multiple-connection application?

Any help would rock, thanks guys.:confused:
 
This is an example, it doesn't take into account clients disconnecting if they don't send a disconnect message, the computer will hold the connection as Active even though it isn't if the disconnect message doesn't arrive

If you want a simple TCP messenging system:
Visual Basic:
Public Shared Sub Main()
Dim TCPListen As Sockets.TCPListener = New Sockets.TCPListener(899) 'Listen to port 899
TCPListen.Listen() 'Start Listener

Dim ActiveClients(0) As Sockets.TCPClient
Dim Running As Boolean, i As Integer
Do While Running
     If TCPListen.Pending Then 'If a connection is waiting to be recieved
           Redim Preserve ActiveClients(ActiveClients.GetUpperBound(0) + 1)
           ActiveClients(ActiveClients.GetUpperBound(0)) = TCPListen.AcceptTcpClient()
    End If

    For i = 1 To ActiveClients.GetUpperBound(0) 'Loop through all the clients
          If ActiveClients(i).GetStream.DataAvaliable Then 'If Data is avaliable
               With ActiveClients(i).GetStream
                      If .ReadByte() = 0 Then ActiveClients(i).Close 'If we recieved a Character 0(Chosen Stutdown command) then terminate
                      'Do stuff with data(Use .ReadByte to get data if it returns -1 then you have recieved all the data you can until more arrives)
               End With
          End If
    Next i
Loop

TcpListen.Stop
End Sub
The client doesn't actually do anything with data just fill in the section specified to get something to happen, the program also won't terminate because Running is always True

To connect to this program you'd use:
Visual Basic:
Dim TCPLink As TCPClient = New TCPClient()
TCPLink.Connect(New IPAddress("192.168.0.1"), 899)

Dim byteData() As Byte = {0}
TCPLink.GetStream.Write(byteData, 0, 1)
TCPLink.Close

There are tutorials around on the Internet but I haven't been able to find a really good one, the Microsoft Quickstart tutorials has some information but one you discover how it works you may have to figure it out for yourself
 
Last edited:
Back
Top