【发布时间】:2019-08-05 16:17:25
【问题描述】:
我正在尝试接收由 Python TCP 客户端发送到 C# 服务器的多条消息。 我确实收到了数据,但一次都收到了,我不希望这种情况发生。 我试图将服务器缓冲区大小设置为我发送的字节 [] 的大小,但它不起作用 (source)。 有什么想法可以解决这个问题吗?
客户端发送代码:
import socket
def send_to_remote(sock, data):
data_bytes = bytearray()
data_bytes.extend(map(ord, data)) # appending the array with string converted to bytes
bytes_length = len(data_bytes) # length of the array that I am sending
sock.setsockopt(socket.SOL_SOCKET, socket.SO_SNDBUF, bytes_length) # setting the buffer size to the array length
print(bytes_length)
sock.send(data_bytes) # sending the data
服务器接收代码:
public static string ReadData(TcpClient connection)
{
StringBuilder receivedDataStr = new StringBuilder();
NetworkStream connectionStream = connection.GetStream();
if (connectionStream.CanRead)
{
byte[] connectionBuffer = new byte[connection.ReceiveBufferSize];
Console.WriteLine(">> Reading from NODE");
int bytesRead = 0;
bytesRead = connectionStream.Read(connectionBuffer, 0, 1024);
receivedDataStr.Append(Encoding.ASCII.GetString(connectionBuffer, 0, bytesRead));
Console.WriteLine(">> " + connection.ReceiveBufferSize);
return receivedDataStr.ToString();
}
else
{
Console.WriteLine(">> Can't read from network stream");
return "none-read";
}
}
编辑:
我做的是:
send_to_remote(socekt, "msg1")
send_to_remote(socekt, "msg1")
然后:
string msg1 = ReadData(client);
string msg2 = ReadData(client);
我收到 106200 的缓冲区数组。
结果是:
"msg1 (then new line) msg2"
"" (string msg2 is waiting for data)
提前谢谢你!!
【问题讨论】:
-
编辑只是证实了我所说的一切...... 您的代码需要查找 CR/LF 并拆分消息并处理尚未完成的积压工作有效载荷(或者,正如我所说:使用
StreamReader为你做这件事)
标签: c# python .net sockets tcp