A TCP client is a process that establishes a connection with a remote TCP server, sends requests to it, and receives replies. When the connection is no longer needed, it is closed. Follow this procedure to set up a TCP client :
| Step | Action |
|---|---|
|
1. |
Create an IPEndPoint Object for the remote server endpoint. This Object should specify the IP address of the remote server and the port number on which the server is listening. |
|
2. |
Create a TcpClient Object using this endpoint_object. Alternately you can create a TcpClient Object omitting the endpoint_object, and later call socket_object.Connect method to establish the connection. |
|
3. |
Obtain the Socket Object for this connection by calling the tcpclient_object.Client method. |
|
4. |
Use socket_object.Send and socket_object.Receive to perform I/O with the remote client. |
|
5. |
When finished with the connection, call socket_object.Close to close it. |
This example shows how to write a TCP client that connects to a TCP server.
The IPEndPoint Objectep for the remote TCP server is set to IP address 192.168.0.2, port 1234. A TcpClient Object, tc is created that connects to that endpoint. The Socket ts is obtained from tc and is used for sending messages and receiving replies.
Public Sub Tcp_client
' Connect to a remote TCP server at
' IP address 192.168.0.2, Port 1234
Dim ep As New IPEndPoint("192.168.0.2", 1234)
Dim tc As New TcpClient(ep)
Dim ts As Socket
Dim message As String
Dim reply As String
Dim ii As Integer
ts = tc.Client
message = "Test message" & Chr(GPL_CR) & Chr(GPL_LF)
ts.Send(message)
ts.Receive(reply, 1000)
Console.Writeline("Reply: " & reply)
For ii = 1 To 100
ts.Send(message)
ts.Receive(reply, 1000)
Next ii
Console.Writeline("Test complete")
ts.Close
End Sub