Sockets... HEEEELLPPP! :)

Hi, everybody.

I'm busy porting over a Telnet server application from VB6 to VB.net. But I've hit two MAJOR hurdles.

The first thing I noticed with VB.net is that there is no Winsock control. Damn. So now I've got to use the System.Net.Sockets. OK. But I also need to use Threading apparently.

I've found this one hell of a learning curve and was just wondering if somebody could post an example of a simple TCP/IP server that listens on a port, accepts multiple connections and sends a message to each user that connects.

Once I've gotten past this stage, my .net blues are over and I can start using the new features!

Cheers, everybody

Will



Answer this question

Sockets... HEEEELLPPP! :)

  • # 2 Dessi

    Jayson, you're a legend! Thank you :)

  • JWM

    Super smashey great!

    All very helpful... thanks, guys!

  • samperiau

    To open and listen on a port you could use this:

    m_TcpListener = New System.Net.Sockets.TcpListener(System.Net.IPAddress.Parse("127.0.0.1"), 11000)

    m_TcpListener.Start()

    Then in some sort of loop or on it's own thread you would use something like this to accept the clients connection:

    If m_TcpListener.Pending Then 'Is connection pending

    Dim s As System.Net.Sockets.TcpClient = m_TcpListener.AcceptTcpClient 'Accept the client

    Dim SW As New System.IO.StreamWriter(s.GetStream) 'Create a streamwriter from the underlying stream

    SW.Write("Use the stream to read and write the socket.") 'Write to it or send data to the client

    m_Sockets.Add(s) 'add the socket to some sort of list for later use



  • CarBENbased

    Guys, just need one more quick bit of advice... I can send information just fine by using the stream provided by 'sw'.

    But how do I receive information from the client

    Also, I'm storing the clients in a list, but when I try to FOR ... NEXT through the list, I'm getting an indexy out of range sort of error. How can I go through a list and pick up each Socket

    All help much appreciated!!

    Will


  • CloseVision

    MSDN provides some pretty good samples - using both synchronous and asychronous methods. I've had to tweak their code a bit to make it work the way I needed.

    http://msdn2.microsoft.com/en-us/library/w89fhyex(vs.80).aspx

    Mike


  • Bigguy Graves

    You're welcome. Have fun coding.

  • dan_muller

    You could use the Stream object instead of the StreamWriter. The Stream object allows you to read an write to the socket.

    Dim s As System.Net.Sockets.TcpClient = m_TcpListener.AcceptTcpClient 'Accept the client
    Dim stream As System.IO.Stream = s.GetStream
    stream.Write(buffer() As Byte, offset As Byte, count As Integer)
    stream.Read(buffer() As Byte, offset As Byte, count As Integer
    ) As Integer

    To pick up each socket use something like this.

    For Each so As System.Net.Sockets.TcpClient In m_Sockets
    'so is each socket
    Nexto



  • Sockets... HEEEELLPPP! :)