溫馨提示×

TouchSocket在C#中如何進行網絡通信

c#
小樊
160
2024-07-17 04:41:44
欄目: 編程語言

在C#中進行網絡通信可以使用Socket類來實現,以下是一個使用Socket類進行網絡通信的示例代碼:

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

public class Client
{
    public static void Main()
    {
        try
        {
            IPAddress ipAddress = IPAddress.Parse("127.0.0.1");
            int port = 8888;

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

            // Connect to the server
            clientSocket.Connect(ipAddress, port);

            // Send data to the server
            string data = "Hello from client";
            byte[] bytes = Encoding.ASCII.GetBytes(data);
            clientSocket.Send(bytes);

            // Receive data from the server
            byte[] buffer = new byte[1024];
            int bytesRead = clientSocket.Receive(buffer);
            string response = Encoding.ASCII.GetString(buffer, 0, bytesRead);
            Console.WriteLine("Server response: " + response);

            // Close the socket
            clientSocket.Shutdown(SocketShutdown.Both);
            clientSocket.Close();
        }
        catch (Exception e)
        {
            Console.WriteLine("Exception: " + e.Message);
        }
    }
}

以上示例代碼展示了一個簡單的客戶端程序,通過Socket類實現了與服務器端的網絡通信。首先創建一個Socket對象并連接到服務器端的IP地址和端口,然后發送數據到服務器端,并接收服務器端返回的數據。最后關閉Socket連接。

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