TCP Server

A TCP server is a process that listens for connection requests and sets up connections with remote TCP clients. The remote clients send requests to the server on the connection and receive responses. When the connection is no longer needed, it is closed. Follow this procedure to set up a TCP server:

Step Action

1.  

Create an IPEndPoint Object for the local endpoint. This Object should leave the IP Address blank, allowing any remote node to connect, but set the port to a specific number that the remote client knows.

2.  

Create a TcpListener Object using this IPEndPoint Object, and start listening for a connection request by calling the tcplistener_object.Start method.

3.  

Optionally poll for a connection request using the tcplistener_object.Pending property.

4.  

Accept the connection request and obtain a new Socket Object by calling the tcplistener_object.AcceptSocket method. If no other connections are to be serviced, stop listening for connections by calling the tcplistener_object.Stop method.

5.  

Use socket_object.Receive and socket_object.Send to perform I/O with the remote client.

6.  

When finished with the connection, call socket_object.Close to close it.

TCP Server Example

In this example, a simple TCP server is created to listen for connections on port 1234. A client may connect from anywhere. The server simply echoes back whatever the client sends. You can use a standard Telnet application to communicate with this server.

The IPEndPoint Objectep for the remote TCP client is set to IP address “”, port 1234, indicating it will connect with any IP address using that port. A TcpListener Object, tl, is created that listens for connections to that endpoint. The Pending method is used to poll for a connection request. When a request arrives, the AcceptSocket method returns a new Socket Objectts that is used for receiving messages and sending replies.

Public Sub Telnet
' Simple Telnet-like TCP server, listening on port 1234
' Echoes back whatever it receives
Dim ep As New IPEndPoint("," 1234) ' Accept from any IP
Dim tl As New TcpListener(ep)
Dim ts As Socket
Dim recv As String
Dim send As String
Dim ii As Integer

' Start listening and wait for a connection

tl.Start()
While Not tl.Pending()
Thread.Sleep(5000)
End While
Console.Writeline("Connection request...")
ts = tl.AcceptSocket() ' Get the socket
tl.Stop() ' Only service one

' Read from client and echo back messages

While True
ii = ts.Receive(recv, 1000)
Console.Writeline("Receive count: " & CStr(ii))
If ii = 0 Then
Exit While
End If

send = "Received: " & recv
ts.Send(send)
End While
Console.Writeline("Connection closed")
ts.Close()
End Sub