TcpClient

In this lesson, we will create a client and establish a connection from the client to the server.

Combine the server‑side code from the previous lesson (TcpListener) with the client‑side implementation in this section (TcpClient) to build a fully‑functional TCP chat tool step‑by‑step.

Key Concept Differences

  1. Server: TcpListener
    Binds to a static IP address plus a fixed port (9500). It passively listens continuously for incoming client connections and can accept multiple clients at the same time. Think of it like a shopkeeper waiting for customers to show up.
  2. Client: TcpClient
    No manual port binding is required. The operating system automatically assigns a random temporary port for initiating an active connection toward the server’s fixed port 9500.

Ports on communicating peers are not equal
Client random port — Server fixed port 9500

Console‑Based Client

using System;
using System.Net.Sockets;

namespace TalkClient
{
    class Program
    {
        static void Main(string[] args)
        {
            // Instantiate TCP client object
            TcpClient tcpClient = new TcpClient();

            // Establish connection to local server 127.0.0.1:9500
            // For remote machines, replace with target host IP. Server and client do not have to run on the same PC.
            tcpClient.Connect("127.0.0.1", 9500);

            // LocalEndPoint: local client IP‑port pair
            // RemoteEndPoint: remote server IP‑port pair
            Console.WriteLine("Connection succeeded. Local endpoint {0}, server endpoint {1}",
                tcpClient.Client.LocalEndPoint,
                tcpClient.Client.RemoteEndPoint);

            Console.ReadLine();
            tcpClient.Close();
        }
    }
}Code language: JavaScript (javascript)

WinForms Client Source Code

UI Controls:

  • textBoxIP: Server IP address
  • textBoxPort: Server port number
  • buttonStart: Connect button
  • textBoxInfo: Message display area
  • textBoxMsg: Input box for outgoing messages
  • buttonSend: Send button
using System;
using System.Net.Sockets;
using System.Windows.Forms;

namespace SocketChatClient
{
    public partial class Form1 : Form
    {
        TcpClient tcpClient;

        public Form1()
        {
            InitializeComponent();
        }

        // Connect‑button click handler
        private void buttonStart_Click(object sender, EventArgs e)
        {
            tcpClient = new TcpClient();
            try
            {
                string ip = textBoxIP.Text;
                int port = Convert.ToInt32(textBoxPort.Text);
                tcpClient.Connect(ip, port);
                textBoxInfo.AppendText($"Connected successfully! Local endpoint: {tcpClient.Client.LocalEndPoint}\r\n");
            }
            catch (Exception ex)
            {
                MessageBox.Show("Connection failed‑" + ex.Message);
            }
        }
    }
}Code language: PHP (php)

Server‑Client Interaction Workflow

  1. Launch the server application first, hit start, call TcpListener.Start() to begin listening on port 9500
  2. Then launch the client application, click connect, TcpClient.Connect() performs the TCP three‑way handshake
  3. After connection setup, bidirectional message exchange happens via NetworkStream (covered in next chapter)

Important Notes

  1. Common connection‑failure causes
  • Wrong startup sequence: server not started beforehand
  • Mismatched IP address or port number
  • Firewall blocking traffic; avoid 127.0.0.1 when debugging across machines, use LAN IP instead
  1. Port fundamentals
  • Server keeps port 9500 fixed and can handle multiple concurrent client connections
  • Client port gets randomly assigned by OS; value changes on each run, no manual assignment needed
  1. Blocking pitfall warning
    Calling .Connect() directly inside WinForms will block the UI thread. Production‑grade projects should prefer async ConnectAsync to prevent UI freezes.

Review: WinForms Server (Previous Lesson)

using System;
using System.Net;
using System.Net.Sockets;
using System.Windows.Forms;

namespace SocketChatServer
{
    public partial class Form1 : Form
    {
        IPAddress ip;
        TcpListener listener;

        public Form1()
        {
            InitializeComponent();
        }

        private void buttonStart_Click(object sender, EventArgs e)
        {
            ip = IPAddress.Parse(textBoxIP.Text);
            int port = Convert.ToInt32(textBoxPort.Text);
            listener = new TcpListener(ip, port);
            listener.Start();

            textBoxInfo.Text = $"Server started {DateTime.Now.ToShortTimeString()}\r\n" + textBoxInfo.Text;
        }
    }
}Code language: C# (cs)

Client

Leave a Reply

Your email address will not be published. Required fields are marked *