溫馨提示×

C#如何實現TCP/IP通信

c#
小樊
392
2024-09-14 23:25:25
欄目: 編程語言

在C#中,可以使用System.Net.Sockets命名空間中的類來實現TCP/IP通信。下面是一個簡單的示例,展示了如何創建一個TCP服務器和客戶端進行通信。

首先,我們創建一個TCP服務器:

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

namespace TcpServer
{
    class Program
    {
        static void Main(string[] args)
        {
            // 創建一個TcpListener實例,監聽指定的IP地址和端口
            TcpListener server = new TcpListener(IPAddress.Any, 8080);
            server.Start();

            Console.WriteLine("服務器已啟動,等待客戶端連接...");

            while (true)
            {
                // 當有客戶端連接時,接受連接并返回一個TcpClient實例
                TcpClient client = server.AcceptTcpClient();
                Console.WriteLine("客戶端已連接:" + client.Client.RemoteEndPoint);

                // 獲取客戶端的網絡流
                NetworkStream stream = client.GetStream();

                // 讀取客戶端發送的數據
                byte[] data = new byte[256];
                int i = stream.Read(data, 0, data.Length);

                // 將接收到的數據轉換為字符串
                string receivedData = Encoding.ASCII.GetString(data, 0, i);
                Console.WriteLine("接收到的數據: " + receivedData);

                // 向客戶端發送響應
                string response = "服務器已收到數據: " + receivedData;
                data = Encoding.ASCII.GetBytes(response);
                stream.Write(data, 0, data.Length);

                // 關閉客戶端連接
                client.Close();
            }
        }
    }
}

接下來,我們創建一個TCP客戶端:

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

namespace TcpClient
{
    class Program
    {
        static void Main(string[] args)
        {
            // 創建一個TcpClient實例,連接到服務器
            TcpClient client = new TcpClient("127.0.0.1", 8080);

            // 獲取服務器的網絡流
            NetworkStream stream = client.GetStream();

            // 向服務器發送數據
            string sendData = "你好,這是一條來自客戶端的消息!";
            byte[] data = Encoding.ASCII.GetBytes(sendData);
            stream.Write(data, 0, data.Length);

            // 從服務器接收響應
            data = new byte[256];
            int i = stream.Read(data, 0, data.Length);

            // 將接收到的數據轉換為字符串
            string receivedData = Encoding.ASCII.GetString(data, 0, i);
            Console.WriteLine("接收到的響應: " + receivedData);

            // 關閉客戶端連接
            client.Close();
        }
    }
}

運行上述代碼,首先啟動TCP服務器,然后啟動TCP客戶端。服務器將接收到客戶端發送的數據,并向客戶端發送響應??蛻舳藢⒔邮盏椒掌鞯捻憫@示在控制臺上。

0
亚洲午夜精品一区二区_中文无码日韩欧免_久久香蕉精品视频_欧美主播一区二区三区美女