クライアント‑サーバー通信

核心原理

TCP接続が確立された後、NetworkStream(ネットワークストリーム)を介してデータを送受信します。
ネットワークはバイト配列 byte[]しか転送できません。テキストは事前にバイトへエンコードし、受信時にデコードして文字列に戻す必要があります。

送信対象はテキストに限らず、ファイルや画像もバイト配列に変換して送信可能です。このセクションではまずテキストチャットを実装します。

主要API解説

  1. サーバー側
    listener.AcceptTcpClient()
  • ブロッキングメソッド(待機処理):実行するとクライアントから接続が来るまでスレッドが一時停止します;
  • クライアントの接続を表す TcpClient オブジェクトを返します;
  • tcpClient.GetStream() でネットワークストリームを取得します。
  1. ネットワークストリームの読み書き
  • stream.Write(バイト配列,開始位置,長さ)データ送信
  • stream.Read(バッファ配列,開始位置,最大読取長)データ受信、実際に読み取ったバイト数を返却
  1. エンコーディングの注意点
    サンプルコードでは Encoding.Unicode(UTF‑16)を使用しています。送信側と受信側のエンコーディングを統一する必要があります。不一致だと文字化けが発生します。

サーバー側 WinForms

コントロール:
textBoxIPtextBoxPorttextBoxInfo(メッセージ表示欄)

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

コントロール:
textBoxIPtextBoxPorttextBoxInfotextBoxInput(入力欄)
buttonStart【接続】、buttonSend【送信】

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)

上記コードはクライアントとサーバー間のメッセージ送信を実装しています。

クライアント‑サーバー通信

コメントを残す

メールアドレスが公開されることはありません。 が付いている欄は必須項目です