我正在通过TCP套接字连接发送大字符串0.443+0.064+-0.120+-0.886+0.15167+-0.26754+0.95153
。
我收到的消息与我发送的字符串不同。它是在随机点切割的,即43+0.064+-0.120+-0.886+0.15167+-0.26754+0
如何确保读取完整的字符串?
这是客户端代码:
public static void SendMessage(string message)
{
if (socketConnection == null)
{
return;
}
using (BinaryWriter writer = new
BinaryWriter(socketConnection.GetStream(), Encoding.ASCII, true))
{
writer.Flush();
writer.Write(message);
writer.Flush();
}
}
这是我的服务器代码:
private void ListenForIncommingRequests()
{
tcpListener = new TcpListener(IPAddress.Parse("127.0.0.1"), 8080);
tcpListener.Start();
connectedTcpClient = tcpListener.AcceptTcpClient();
using (BinaryReader reader = new
BinaryReader(connectedTcpClient.GetStream()))
{
while (true)
{
string clientMessage = reader.ReadString();
}
}
}
答案 0 :(得分:2)
正如@NineBerry在评论中指出的那样,您正在编写ASCII编码的字节,但是正在读取默认(Unicode(UTF-16))编码的字节。确保在两端使用相同的编码,我建议使用Unicode,因此在实例化BinaryWriter时删除foreach($list as $item) {
foreach($item['products'] as $product) {
$wName = $item['warehouse']['warehouseName'];
$wType = $item['warehouse']['warehouseType'];
$pr =implode(',',$product);
printf("%s,%s,%s".PHP_EOL,$wName,$wType,$pr);
}
}
或在实例化BinaryWriter和BinaryReader时使用Encoding.ASCII