溫馨提示×

c# socket如何實(shí)現(xiàn)通信

c#
小樊
81
2024-10-09 04:33:29
欄目: 編程語言

在C#中,使用Socket類可以實(shí)現(xiàn)客戶端和服務(wù)器之間的通信。下面是一個(gè)簡單的示例,展示了如何使用Socket類創(chuàng)建一個(gè)TCP服務(wù)器和客戶端并進(jìn)行通信。

1. 創(chuàng)建TCP服務(wù)器

using System;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks;

class TcpServer
{
    static void Main(string[] args)
    {
        int port = 5000;
        IPAddress localAddr = IPAddress.Parse("127.0.0.1");

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

        try
        {
            listener.Bind(new IPEndPoint(localAddr, port));
            listener.Listen(10);

            while (true)
            {
                Console.WriteLine("等待客戶端連接...");
                Socket handler = listener.Accept();
                string data = null;

                // 讀取客戶端發(fā)送的數(shù)據(jù)
                byte[] bytes = new byte[1024];
                int i = handler.Receive(bytes);
                data += Encoding.ASCII.GetString(bytes, 0, i);

                Console.WriteLine("收到消息: " + data);

                // 向客戶端發(fā)送數(shù)據(jù)
                string response = "服務(wù)器已收到消息";
                byte[] msg = Encoding.ASCII.GetBytes(response);
                handler.Send(msg);

                handler.Shutdown(SocketShutdown.Both);
                handler.Close();
            }
        }
        catch (Exception e)
        {
            Console.WriteLine("發(fā)生錯(cuò)誤: " + e.ToString());
        }
        finally
        {
            listener.Close();
        }
    }
}

2. 創(chuàng)建TCP客戶端

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

class TcpClient
{
    static void Main(string[] args)
    {
        string server = "127.0.0.1";
        int port = 5000;

        try
        {
            Socket client = new Socket(IPAddress.Parse(server).AddressFamily, SocketType.Stream, ProtocolType.Tcp);

            client.Connect(new IPEndPoint(IPAddress.Parse(server), port));

            string message = "你好,服務(wù)器!";
            byte[] msg = Encoding.ASCII.GetBytes(message);
            client.Send(msg);

            byte[] bytes = new byte[1024];
            int i = client.Receive(bytes);
            string response = Encoding.ASCII.GetString(bytes, 0, i);
            Console.WriteLine("收到消息: " + response);

            client.Shutdown(SocketShutdown.Both);
            client.Close();
        }
        catch (Exception e)
        {
            Console.WriteLine("發(fā)生錯(cuò)誤: " + e.ToString());
        }
    }
}

在這個(gè)示例中,我們創(chuàng)建了一個(gè)TCP服務(wù)器,監(jiān)聽端口5000上的客戶端連接。當(dāng)客戶端連接到服務(wù)器時(shí),服務(wù)器會(huì)讀取客戶端發(fā)送的數(shù)據(jù),并向客戶端發(fā)送確認(rèn)消息。同樣,我們也創(chuàng)建了一個(gè)TCP客戶端,連接到服務(wù)器并發(fā)送一條消息,然后接收服務(wù)器的響應(yīng)。

請注意,這個(gè)示例僅用于演示目的,實(shí)際應(yīng)用中可能需要考慮更多的錯(cuò)誤處理和功能實(shí)現(xiàn)。

0