使用TCP/套接字将字符串列表从Python发送到C#



使用TCP/套接字将字符串列表从python服务器发送到C#客户端的首选方式是什么
我遇到过一些不太相关的消息来源,但到目前为止,还没有任何具体解决这个问题的消息(从我有限的网络背景来看(。

一个简单的例子将不胜感激!

谢谢!

有一些方法可以实现这一目标。使用套接字连接时,必须像处理字节一样处理数据。因此,与字符串处理(您有一个空字节来标识char数组的末尾(不同,您不知道字节数组的末尾在哪里。因此,建立缓冲区大小并识别字符串的结尾是一种很好的做法

一种解决方案,无需错误处理即可简化读数:

Python客户端:

import socket
host = "127.0.0.1"
port = 8080
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
dest = (host, port)
sock.setsockopt(socket.SOL_SOCKET, socket.SO_SNDBUF, 256) #256 -> expected packet length
print("Connecting ...")
sock.connect(dest)
print("OK")
list = ["first string", "second string", "third string"]
for i in range(len(list)):
sock.send(str.encode(list[i] + "$"))
print("Sending " + list[i])
sock.close()

C#Tcp侦听器:

using System.Net.Sockets;
using System.Text;
TcpListener listener = new TcpListener(System.Net.IPAddress.Any, 8080);
listener.Start();
Console.WriteLine("Waiting for TCP connection ...");
TcpClient tcp = listener.AcceptTcpClient();
tcp.ReceiveBufferSize = 256; //Expected packet length in bytes
Console.WriteLine("Receiving string list ...");
int received_bytes_count = -1;
byte[] total_buffer = new byte[1024]; //Expected total bytes in a string list
while(received_bytes_count != 0)
{
int total_buffer_index = received_bytes_count + 1;
NetworkStream ns = tcp.GetStream();
byte[] buffer = new byte[tcp.ReceiveBufferSize];
received_bytes_count = ns.Read(buffer, 0, buffer.Length);
buffer.CopyTo(total_buffer, total_buffer_index);
}
List<string> list = new List<string>();
list.AddRange(Encoding.ASCII.GetString(total_buffer).Split('$'));
list.RemoveAt(list.Count - 1); //remove the null string after the last '$'
tcp.Close();
foreach (string s in list.ToArray())
Console.WriteLine(s);

在这个例子中,我将256字节固定为数据包大小,将1024字节固定为字符串列表大小。我已经使用$来识别每个字符串的末尾。

在C#Tcp Listener中,我使用了Encoding.ASCII.GetString()将字节数组转换为字符串,并使用Split()函数将接收到的字符串总数除以字符串列表。我删除了最后一个字符串(在最后一个$之后(,因为它是0字节序列(缓冲区的末尾(。

请注意,套接字由操作系统处理,因此这并不意味着每个send()Read()函数都代表一个网络数据包。因此,使用缓冲区大小选项非常重要。再举一个例子,有一个旨在减少网络流量的Nagle算法,操作系统会等待一段时间来收集应用程序使用send()功能发送的数据,因此会将所有数据一起发送一个数据包,而不是发送一些小数据包,这些小数据包会通过更多的控制数据来增加网络流量。您可以使用setsockopt()关闭Nagle算法以提高性能,但我认为您想要的应用程序并非如此。只需要理解一个send()函数并不意味着一个数据包,也不意味着一台服务器的Read()函数只接收一台客户端的send()函数的数据。有关Nagle算法的更多详细信息:https://learn.microsoft.com/en-us/dotnet/api/system.net.sockets.socket.nodelay?view=net-6.0

使用JSON:["string 1", "string 2", "string 3"]如果您的Python服务器可以使用HTTP协议(有多种实现(,那么您可以简单地使用.NET中内置的任何HTTP客户端

using System.Text.Json;
using var client = new HttpClient();
var content = await client.GetStringAsync("http://your.server/url");
Console.WriteLine(content);
var stringArray = JsonSerializer.Deserialize<string[]>(content);

最新更新