Quick example of a socket listener

Imports System.Net
Imports System.Net.Sockets
Imports System.Text

Module Module1

    Sub Main()

        ' To test once this program is running: Telnet localhost 8000

        ' Must listen on correct port- must be same as port client wants to connect on.
        Const portNumber As Integer = 8000
        Dim IPAddr As IPAddress = IPAddress.Parse("127.0.0.1")
        Dim tcpListener As New TcpListener(IPAddr, 8000)

        tcpListener.Start()
        Console.WriteLine("Waiting for connection...")

        Try
            'Accept the pending client connection and return
            'a TcpClient initialized for communication.
            Dim tcpClient As TcpClient = tcpListener.AcceptTcpClient()
            Console.WriteLine("Connection accepted.")

            ' Get the stream
            Dim networkStream As NetworkStream = tcpClient.GetStream()

            ' Read the stream into a byte array
            Dim bytes(tcpClient.ReceiveBufferSize) As Byte
            networkStream.Read(bytes, 0, CInt(tcpClient.ReceiveBufferSize))

            ' Return the data received from the client to the console.
            Dim clientdata As String = Encoding.ASCII.GetString(bytes)
            Console.WriteLine(("Client sent: " + clientdata))
            Dim responseString As String = "Connected to server."
            Dim sendBytes As [Byte]() = Encoding.ASCII.GetBytes(responseString)
            networkStream.Write(sendBytes, 0, sendBytes.Length)
            Console.WriteLine(("Message Sent /> : " + responseString))

            'Any communication with the remote client using the TcpClient can go here.

            'Close TcpListener and TcpClient.
            tcpClient.Close()
            tcpListener.Stop()
            Console.WriteLine("exit")

            'Wait for Return/Enter before closing program
            Console.ReadLine()

        Catch e As Exception
            Console.WriteLine(e.ToString())
            Console.ReadLine()
        End Try

    End Sub

End Module
Reply
This site contains copyrighted material the use of which has not always been specifically authorized by the copyright owner. We are making such material available in our efforts to advance understanding of environmental, political, human rights, economic, democracy, scientific, and social justice issues, etc. We believe this constitutes a 'fair use' of any such copyrighted material as provided for in section 107 of the US Copyright Law. In accordance with Title 17 U.S.C. Section 107, the material on this site is distributed without profit to those who have expressed a prior interest in receiving the included information for research and educational purposes. For more information go to: http://www.law.cornell.edu/uscode/17/107.shtml . If you wish to use copyrighted material from this site for purposes of your own that go beyond 'fair use', you must obtain permission from the copyright owner.