温馨提示×

c# linux开发怎样实现网络通信

c#
小樊
81
2024-12-09 23:42:49
栏目: 编程语言

在C#中进行Linux开发并实现网络通信,你可以使用.NET Core或.NET 5/6/7等跨平台框架。以下是一个简单的示例,展示了如何使用C#和.NET Core在Linux上实现TCP网络通信。

服务器端

  1. 创建一个新的控制台应用程序

    dotnet new console -o NetworkCommunicationServer
    cd NetworkCommunicationServer
    
  2. 添加必要的NuGet包

    dotnet add package System.Net.Sockets
    
  3. 编写服务器代码

    using System;
    using System.Net;
    using System.Net.Sockets;
    using System.Text;
    using System.Threading.Tasks;
    
    class Program
    {
        static async Task Main(string[] args)
        {
            // 监听端口
            int port = 5000;
            IPAddress ipAddress = IPAddress.Any;
            TcpListener server = null;
    
            try
            {
                server = new TcpListener(ipAddress, port);
                Console.WriteLine($"Server started on {ipAddress}:{port}");
    
                // 开始监听连接
                server.Start();
    
                while (true)
                {
                    // 等待客户端连接
                    Console.Write("Waiting for client connection...");
                    TcpClient client = await server.AcceptTcpClientAsync();
                    Console.WriteLine("Client connected!");
    
                    // 处理客户端请求
                    HandleClient(client);
                }
            }
            catch (Exception e)
            {
                Console.WriteLine($"Error: {e.Message}");
            }
            finally
            {
                server?.Stop();
            }
        }
    
        static async Task HandleClient(TcpClient client)
        {
            NetworkStream stream = client.GetStream();
            byte[] buffer = new byte[1024];
            int bytesRead;
    
            // 读取客户端发送的数据
            while ((bytesRead = await stream.ReadAsync(buffer, 0, buffer.Length)) != 0)
            {
                string data = Encoding.UTF8.GetString(buffer, 0, bytesRead);
                Console.WriteLine($"Received: {data}");
    
                // 发送响应给客户端
                string response = "Hello from server!";
                byte[] responseBytes = Encoding.UTF8.GetBytes(response);
                await stream.WriteAsync(responseBytes, 0, responseBytes.Length);
            }
    
            client.Close();
            Console.WriteLine("Client disconnected.");
        }
    }
    

客户端

  1. 创建一个新的控制台应用程序

    dotnet new console -o NetworkCommunicationClient
    cd NetworkCommunicationClient
    
  2. 添加必要的NuGet包

    dotnet add package System.Net.Sockets
    
  3. 编写客户端代码

    using System;
    using System.Net;
    using System.Net.Sockets;
    using System.Text;
    using System.Threading.Tasks;
    
    class Program
    {
        static async Task Main(string[] args)
        {
            // 服务器地址和端口
            string serverAddress = "127.0.0.1";
            int serverPort = 5000;
    
            // 创建TCP客户端
            TcpClient client = new TcpClient(serverAddress, serverPort);
            NetworkStream stream = client.GetStream();
            byte[] buffer = new byte[1024];
            int bytesRead;
    
            // 发送数据给服务器
            string message = "Hello from client!";
            byte[] messageBytes = Encoding.UTF8.GetBytes(message);
            await stream.WriteAsync(messageBytes, 0, messageBytes.Length);
    
            // 读取服务器的响应
            while ((bytesRead = await stream.ReadAsync(buffer, 0, buffer.Length)) != 0)
            {
                string response = Encoding.UTF8.GetString(buffer, 0, bytesRead);
                Console.WriteLine($"Received: {response}");
            }
    
            client.Close();
            Console.WriteLine("Disconnected from server.");
        }
    }
    

运行示例

  1. 启动服务器: 在NetworkCommunicationServer目录下运行以下命令:

    dotnet run
    
  2. 启动客户端: 在NetworkCommunicationClient目录下运行以下命令:

    dotnet run
    

你应该会看到服务器和客户端之间的消息传递。

其他网络通信方式

除了TCP,你还可以使用UDP、HTTP/HTTPS、WebSocket等进行网络通信。以下是一些示例:

UDP通信

服务器端

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

class Program
{
    static async Task Main(string[] args)
    {
        int port = 5001;
        IPAddress ipAddress = IPAddress.Any;
        UdpClient udpServer = null;

        try
        {
            udpServer = new UdpClient(port);
            Console.WriteLine($"UDP Server started on {ipAddress}:{port}");

            while (true)
            {
                byte[] bytesReceived = await udpServer.ReceiveAsync();
                string receivedData = Encoding.UTF8.GetString(bytesReceived.Buffer, 0, bytesReceived.BytesReceived);
                Console.WriteLine($"Received: {receivedData}");

                string response = "Hello from UDP server!";
                byte[] responseBytes = Encoding.UTF8.GetBytes(response);
                udpServer.Send(responseBytes, responseBytes.Length, bytesReceived.RemoteEndPoint);
            }
        }
        catch (Exception e)
        {
            Console.WriteLine($"Error: {e.Message}");
        }
        finally
        {
            udpServer?.Close();
        }
    }
}

客户端

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

class Program
{
    static async Task Main(string[] args)
    {
        string serverAddress = "127.0.0.1";
        int serverPort = 5001;

        UdpClient udpClient = new UdpClient();
        IPEndPoint serverEndPoint = new IPEndPoint(IPAddress.Parse(serverAddress), serverPort);

        string message = "Hello from UDP client!";
        byte[] messageBytes = Encoding.UTF8.GetBytes(message);
        udpClient.Send(messageBytes, messageBytes.Length, serverEndPoint);

        byte[] bytesReceived = await udpClient.ReceiveAsync();
        string response = Encoding.UTF8.GetString(bytesReceived.Buffer, 0, bytesReceived.BytesReceived);
        Console.WriteLine($"Received: {response}");

        udpClient.Close();
        Console.WriteLine("Disconnected from UDP server.");
    }
}

HTTP/HTTPS通信

你可以使用HttpClient类进行HTTP请求和响应处理。

服务器端(使用ASP.NET Core):

using System;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;

namespace NetworkCommunicationServer
{
    public class Startup
    {
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }

            app.UseRouting();

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapGet("/", async context =>
                {
                    await context.Response.WriteAsync("Hello from server!");
                });
            });
        }
    }
}

客户端

using System;
using System.Net.Http;
using System.Threading.Tasks;

class Program
{
    static async Task Main(string[] args)
    {
        using var httpClient = new HttpClient();
        HttpResponseMessage response = await httpClient.GetAsync("http://127.0.0.1:5000");
        string responseBody = await response.Content.ReadAsStringAsync();
        Console.WriteLine(responseBody);
    }
}

WebSocket通信

服务器端(使用ASP.NET Core):

using System;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.WebSockets;

namespace NetworkCommunicationServer
{
    public class Startup
    {
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddControllersWithViews();
            services.AddWebSocket();
        }

        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }

            app.UseRouting();

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllerRoute(
                    name: "default",
                    pattern: "{controller=Home}/{action=Index}/{id?}");

                endpoints.MapWebSocket("/ws", new WebSocketOptions()
                {
                    KeepAliveInterval = TimeSpan.Zero,
                    CloseTimeout = TimeSpan.Zero
                });
            });
        }
    }

    public class HomeController : Controller
    {
        [HttpGet]
        public IActionResult Index()
        {
            return View();
        }

        [HttpGet("ws")]
        public async Task<IActionResult> WebSocket(WebSocketContext context)
        {
            byte[] buffer = new byte[1024 * 4];
            WebSocketReceiveResult result;

            do
            {
                result = await context.接收Async(new ArraySegment<byte>(buffer));
                string message = Encoding.UTF8.GetString(buffer, 0, result.Count);
                Console.WriteLine($"Received: {message}");

                string response = "Hello from server!";
                byte[] responseBytes = Encoding.UTF8.GetBytes(response);
                await context.SendAsync(new ArraySegment<byte>(responseBytes));
            } while (!result.CloseStatus.HasValue);

            return new EmptyResult();
        }
    }
}

客户端

using System;
using System.Net.WebSockets;
using System.Threading.Tasks;

class Program
{
    static async Task Main(string[] args)
    {
        using var socket = new ClientWebSocket();
        await socket.ConnectAsync("ws://127.0.0.1:5000/ws", CancellationToken.None);

        string message = "Hello from client!";
        byte[] messageBytes = Encoding.UTF8.GetBytes(message);
        await socket.SendAsync(new ArraySegment<byte>(messageBytes), WebSocketMessageType.Text, true);

        byte[] buffer = new byte[1024 * 4];
        WebSocketReceiveResult result;

        do
        {
            result = await socket.ReceiveAsync(new ArraySegment<byte>(buffer), CancellationToken.None);
            string response = Encoding.UTF8.GetString(buffer, 0, result.Count);
            Console.WriteLine($"Received: {response}");
        } while (!result.CloseStatus.HasValue);

        socket.CloseAsync(WebSocketCloseStatus.NormalClosure, "Goodbye from client!", CancellationToken.None).Wait();
    }
}

这些示例展示了如何在C#中使用.NET Core在Linux上实现不同类型的网络通信。你可以根据需要选择合适的方式进行通信。

0