首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> C語言 >> 關於C語言

C# 同步 Socket 伺服器範例 — 阻塞式 Accept/Receive

     編輯:關於C語言

同步伺服器特徵

  • listener.Accept() 阻塞直到用戶端連線。
  • handler.Receive() 阻塞直到收到資料。
  • 單執行緒循序處理,適合教學/低併發場景。

完整程式碼


using System;
using System.Net;
using System.Net.Sockets;
using System.Text;

public class SynchronousSocketListener
{
    public static string Data = null;

    public static void StartListening()
    {
        byte[] bytes = new byte[1024];
        IPHostEntry ipHost = Dns.GetHostEntry(Dns.GetHostName());
        IPAddress ipAddr = ipHost.AddressList[0];
        IPEndPoint localEP = new IPEndPoint(ipAddr, 11000);

        Socket listener = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

        try
        {
            listener.Bind(localEP);
            listener.Listen(10);

            while (true)
            {
                Console.WriteLine("等待連線...");
                Socket handler = listener.Accept(); // 阻塞
                Data = null;

                while (true)
                {
                    bytes = new byte[1024];
                    int bytesRec = handler.Receive(bytes); // 阻塞
                    Data += Encoding.ASCII.GetString(bytes, 0, bytesRec);
                    if (Data.IndexOf("") > -1) break; // 訊息結束標記
                }

                Console.WriteLine($"收到訊息: {Data}");
                byte[] msg = Encoding.ASCII.GetBytes(Data);
                handler.Send(msg); // 回應
                handler.Shutdown(SocketShutdown.Both);
                handler.Close();
            }
        }
        catch (Exception ex)
        {
            Console.WriteLine(ex.ToString());
        }
        Console.WriteLine("\n按 Enter 結束...");
        Console.Read();
    }

    public static int Main(string[] args)
    {
        StartListening();
        return 0;
    }
}

關鍵點

  • 通訊協定:用戶端訊息**必須包含 ``** 作為結束標記,伺服器才會停止接收並處理。
  • Encoding.ASCII 編碼/解碼,中文需改用 UTF8。
  • Shutdown(SocketShutdown.Both) 禁用收發再 Close 釋放。
  • 生產環境高併發請改用**非同步 Socket** (BeginAccept/BeginReceive) 或 SocketAsyncEventArgs。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved