Client‑Server Communication

Core Principles

After a TCP connection is established, data is transferred via the NetworkStream;
Networks can only transmit byte arrays byte[]. Text must first be encoded into bytes, then decoded back into strings upon reception.

Transmission is not limited to text. Files and images can also be converted to byte arrays for transfer. This section implements text‑based chat first.

Key API Reference

  1. Server‑Side
    listener.AcceptTcpClient()
  • Blocking Method (Interrupt‑wait): The thread pauses at this call until a client initiates a connection;
  • Returns a TcpClient object representing this client connection;
  • Obtain the network stream with tcpClient.GetStream().
  1. Network Stream Read & Write
  • stream.Write(byte array, offset, length): Send data
  • stream.Read(buffer array, offset, max read length): Receive data, returns the actual number of bytes read
  1. Encoding Notes
    The course samples use Encoding.Unicode (UTF‑16). Both sender and receiver must use identical encoding, otherwise garbled text will occur.

WinForms Server

Controls:
textBoxIP, textBoxPort, textBoxInfo (message display box)

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

namespace TcpServer
{
    public partial class Form1 : Form
    {
        IPAddress ip;
        TcpListener listener;
        TcpClient tcpClient;

        public Form1()
        {
            InitializeComponent();
        }

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

            textBoxInfo.Text = $"服务器启动-{DateTime.Now.ToShortTimeString()}\r\n" + textBoxInfo.Text;

            // 阻塞!主线程卡住
            tcpClient = listener.AcceptTcpClient();
            textBoxInfo.Text = $"连接成功-{DateTime.Now.ToShortTimeString()}\r\n" + textBoxInfo.Text;

            NetworkStream stream = tcpClient.GetStream();
            byte[] byteArray = new byte[1024];

            // 阻塞等待客户端发送消息
            int length = stream.Read(byteArray, 0, 1024);
            string receiveMessage = Encoding.Unicode.GetString(byteArray, 0, length);

            textBoxInfo.Text = $"接收到:{receiveMessage}-{DateTime.Now.ToShortTimeString()}\r\n" + textBoxInfo.Text;
        }
    }
}Code language: PHP (php)

WinForms Client

Controls:
textBoxIP, textBoxPort, textBoxInfo, textBoxInput (input box)
buttonStart【Connect】, buttonSend【Send】

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

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

        public Form1()
        {
            InitializeComponent();
        }

        private void buttonStart_Click(object sender, EventArgs e)
        {
            tcpClient = new TcpClient();
            try
            {
                tcpClient.Connect(textBoxIP.Text, Convert.ToInt32(textBoxPort.Text));
                textBoxInfo.AppendText("连接成功!\r\n");
            }
            catch (Exception ex)
            {
                MessageBox.Show("连接失败-" + ex.Message);
            }
        }

        private void buttonSend_Click(object sender, EventArgs e)
        {
            string message = textBoxInput.Text;
            textBoxInfo.Text = $"发送“{message}”-{DateTime.Now.ToShortTimeString()}\r\n" + textBoxInfo.Text;

            NetworkStream stream = tcpClient.GetStream();
            byte[] byteArray = Encoding.Unicode.GetBytes(message);
            stream.Write(byteArray, 0, byteArray.Length);
        }
    }
}Code language: PHP (php)

The above code implements message transmission between client and server.

Client‑Server Communication

Previous:

Leave a Reply

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