首页
学习
活动
专区
工具
TVP
发布
精选内容/技术社群/优惠产品,尽在小程序
立即前往

如何在C#和python应用程序之间建立快速通信?

在C#和Python应用程序之间建立快速通信可以通过多种方式实现,以下是几种常见的方法:

1. 使用TCP/IP套接字

TCP/IP套接字是一种基础的通信方式,适用于需要可靠数据传输的场景。

C# 服务器端示例:

代码语言:txt
复制
using System;
using System.Net;
using System.Net.Sockets;
using System.Text;

class TcpServer
{
    static void Main()
    {
        int port = 5000;
        TcpListener listener = new TcpListener(IPAddress.Any, port);
        listener.Start();
        Console.WriteLine("Server started...");

        while (true)
        {
            TcpClient client = listener.AcceptTcpClient();
            NetworkStream stream = client.GetStream();
            byte[] buffer = new byte[1024];
            int bytesRead = stream.Read(buffer, 0, buffer.Length);
            string data = Encoding.ASCII.GetString(buffer, 0, bytesRead);
            Console.WriteLine("Received: " + data);

            string response = "Hello from C# server!";
            byte[] responseBytes = Encoding.ASCII.GetBytes(response);
            stream.Write(responseBytes, 0, responseBytes.Length);
            client.Close();
        }
    }
}

Python 客户端示例:

代码语言:txt
复制
import socket

def run_client():
    host = '127.0.0.1'
    port = 5000

    client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    client_socket.connect((host, port))

    message = "Hello from Python client!"
    client_socket.send(message.encode('ascii'))

    data = client_socket.recv(1024)
    print('Received: ', repr(data))

    client_socket.close()

if __name__ == '__main__':
    run_client()

2. 使用HTTP/REST API

HTTP/REST API是一种基于HTTP协议的通信方式,适用于需要跨平台、跨语言通信的场景。

C# Web API 示例:

代码语言:txt
复制
using System;
using System.Net;
using System.Net.Http;
using System.Web.Http;

public class MessagesController : ApiController
{
    public IHttpActionResult Get()
    {
        return Ok("Hello from C# Web API!");
    }
}

Python 客户端示例:

代码语言:txt
复制
import requests

def run_client():
    url = 'http://localhost:5000/api/messages'
    response = requests.get(url)
    print('Received: ', response.text)

if __name__ == '__main__':
    run_client()

3. 使用消息队列

消息队列是一种异步通信方式,适用于需要高吞吐量、解耦的场景。常见的消息队列系统包括RabbitMQ、Kafka等。

C# 生产者示例(使用RabbitMQ):

代码语言:txt
复制
using System;
using RabbitMQ.Client;
using System.Text;

class Send
{
    public static void Main()
    {
        var factory = new ConnectionFactory() { HostName = "localhost" };
        using (var connection = factory.CreateConnection())
        using (var channel = connection.CreateModel())
        {
            channel.QueueDeclare(queue: "hello",
                                 durable: false,
                                 exclusive: false,
                                 autoDelete: false,
                                 arguments: null);

            string message = "Hello World!";
            var body = Encoding.UTF8.GetBytes(message);

            channel.BasicPublish(exchange: "",
                                 routingKey: "hello",
                                 basicProperties: null,
                                 body: body);
            Console.WriteLine(" [x] Sent {0}", message);
        }

        Console.WriteLine(" Press [enter] to exit.");
        Console.ReadLine();
    }
}

Python 消费者示例(使用RabbitMQ):

代码语言:txt
复制
import pika

def callback(ch, method, properties, body):
    print(" [x] Received %r" % body)

def run_consumer():
    connection = pika.BlockingConnection(pika.ConnectionParameters('localhost'))
    channel = connection.channel()

    channel.queue_declare(queue='hello')

    channel.basic_consume(queue='hello',
                          on_message_callback=callback,
                          auto_ack=True)

    print(' [*] Waiting for messages. To exit press CTRL+C')
    channel.start_consuming()

if __name__ == '__main__':
    run_consumer()

4. 使用WebSocket

WebSocket是一种双向通信协议,适用于需要实时通信的场景。

C# WebSocket 服务器端示例:

代码语言:txt
复制
using System;
using System.Net.WebSockets;
using System.Text;
using System.Threading.Tasks;

class WebSocketServer
{
    static async Task Main(string[] args)
    {
        var webSocketListener = new HttpListener();
        webSocketListener.Prefixes.Add("ws://localhost:8080/");
        webSocketListener.Start();
        Console.WriteLine("WebSocket server started...");

        while (true)
        {
            var context = await webSocketListener.GetContextAsync();
            if (context.Request.IsWebSocketRequest)
            {
                var webSocketContext = await context.AcceptWebSocketAsync(null);
                var webSocket = webSocketContext.WebSocket;

                byte[] buffer = new byte[1024];
                int bytesRead = await webSocket.ReceiveAsync(new ArraySegment<byte>(buffer), CancellationToken.None);
                string data = Encoding.ASCII.GetString(buffer, 0, bytesRead);
                Console.WriteLine("Received: " + data);

                string response = "Hello from C# WebSocket server!";
                byte[] responseBytes = Encoding.ASCII.GetBytes(response);
                await webSocket.SendAsync(new ArraySegment<byte>(responseBytes), WebSocketMessageType.Text, true, CancellationToken.None);
            }
        }
    }
}

Python WebSocket 客户端示例:

代码语言:txt
复制
import asyncio
import websockets

async def hello():
    uri = "ws://localhost:8080/"
    async with websockets.connect(uri) as websocket:
        await websocket.send("Hello from Python WebSocket client!")
        response = await websocket.recv()
        print('Received: ', response)

if __name__ == "__main__":
    asyncio.get_event_loop().run_until_complete(hello())

总结

选择哪种通信方式取决于具体的应用场景和需求:

  • TCP/IP套接字:适用于需要可靠数据传输的场景。
  • HTTP/REST API:适用于需要跨平台、跨语言通信的场景。
  • 消息队列:适用于需要高吞吐量、解耦的场景。
  • WebSocket:适用于需要实时通信的场景。

每种方式都有其优势和适用场景,可以根据具体需求选择最合适的方法。

页面内容是否对你有帮助?
有帮助
没帮助

相关·内容

没有搜到相关的视频

领券