在C#和Python应用程序之间建立快速通信可以通过多种方式实现,以下是几种常见的方法:
TCP/IP套接字是一种基础的通信方式,适用于需要可靠数据传输的场景。
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();
}
}
}
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()
HTTP/REST API是一种基于HTTP协议的通信方式,适用于需要跨平台、跨语言通信的场景。
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!");
}
}
import requests
def run_client():
url = 'http://localhost:5000/api/messages'
response = requests.get(url)
print('Received: ', response.text)
if __name__ == '__main__':
run_client()
消息队列是一种异步通信方式,适用于需要高吞吐量、解耦的场景。常见的消息队列系统包括RabbitMQ、Kafka等。
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();
}
}
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()
WebSocket是一种双向通信协议,适用于需要实时通信的场景。
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);
}
}
}
}
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())
选择哪种通信方式取决于具体的应用场景和需求:
每种方式都有其优势和适用场景,可以根据具体需求选择最合适的方法。
领取专属 10元无门槛券
手把手带您无忧上云