我正在尝试接收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)
提前谢谢你!啊!