TcpClient.Read从TcpClient.Write读取了错误的值
本文关键字:TcpClient 错误 读取 Read Write | 更新日期: 2023-09-27 18:27:57
你好,我认为我的服务器从TcpClien中读取了错误的值。写它应该是52(发送时的长度字节数组),但在服务器端,当我在TcpClient中查看大小时。读它是8192。我做错了什么?
我的客户:
using System;
using System.Windows.Forms;
using System.Net.Sockets;
using System.Text;
using System.Text.RegularExpressions;
using System.Net;
using System.Xml;
using System.Xml.Linq;
using System.IO;
using System.Text.RegularExpressions;
namespace client
{
public partial class Form1 : Form
{
TcpClient clientSocket = new TcpClient();
NetworkStream serverStream;
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
textBox1.Multiline = true;
msg("Client Started");
label1.Text = "Client Socket Program - ";
}
private void button1_Click(object sender, EventArgs e)
{
Send();
}
public void msg(string mesg)
{
textBox1.Text = textBox1.Text + Environment.NewLine + " >> " + mesg;
}
private void button2_Click(object sender, EventArgs e)
{
clientSocket.Connect("192.168.1.109", 8888);
label1.Text = "Client Socket Program - Server Connected ...";
}
private void Send()
{
NetworkStream serverStream = clientSocket.GetStream();
XElement outXML =XElement.Load("test.xml") ;
byte[] outStream = ConvertXmlToByteArray(outXML, Encoding.UTF8);
serverStream.Write(outStream, 0, outStream.Length);
serverStream.Flush();
}
byte[] ConvertXmlToByteArray(XElement xml, Encoding encoding)
{
using (MemoryStream stream = new MemoryStream())
{
XmlWriterSettings settings = new XmlWriterSettings();
settings.Encoding = encoding;
settings.OmitXmlDeclaration = true; // No prolog
using (XmlWriter writer = XmlWriter.Create(stream, settings))
{
xml.Save(writer);
}
return stream.ToArray();
}
}
}
}
我的服务器
using System;
using System.Threading;
using System.Net.Sockets;
using System.Net;
using System.Text;
using System.Xml;
using System.IO;
using System.Xml.Linq;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
TcpListener serverSocket = new TcpListener(8888);
TcpClient clientSocket = new TcpClient();
int counter = 0;
serverSocket.Start();
Console.WriteLine(" >> " + "Server Started");
counter = 0;
while (true)
{
counter += 1;
clientSocket = serverSocket.AcceptTcpClient();
Console.WriteLine(" >> " + "Client No:" + Convert.ToString(counter) + " started!");
handleClinet client = new handleClinet();
client.startClient(clientSocket, Convert.ToString(counter));
}
clientSocket.Close();
serverSocket.Stop();
Console.WriteLine(" >> " + "exit");
Console.ReadLine();
}
}
//Class to handle each client request separatly
public class handleClinet
{
TcpClient clientSocket;
string clNo;
public void startClient(TcpClient inClientSocket, string clineNo)
{
this.clientSocket = inClientSocket;
this.clNo = clineNo;
Thread ctThread = new Thread(doChat);
ctThread.Start();
}
private void doChat()
{
int requestCount = 0;
requestCount = 0;
while ((true))
{
byte[] bytesFrom = new byte[(int)clientSocket.ReceiveBufferSize];
requestCount = requestCount + 1;
NetworkStream networkStream = clientSocket.GetStream();
networkStream.Read(bytesFrom, 0, (int)clientSocket.ReceiveBufferSize);
Console.Write(clientSocket.ReceiveBufferSize.ToString());
XElement inXML = ConvertByteArrayToXml(bytesFrom);
inXML.Save("jest2.xml");
//XMLSave(dataFromClient);
}
}
//private void XMLSave(string inner)
//{
// XmlDocument XmlDoc = new XmlDocument();
// XmlDoc.Load("jest.xml");
// XmlDeclaration xmlDeclaration = XmlDoc.CreateXmlDeclaration("1.0", "utf-8", null);
// XmlNode nextNode = XmlDoc.CreateElement("root");
// nextNode.InnerText = inner;
// XmlDoc.DocumentElement.AppendChild(nextNode);
// XmlDoc.Save("jest.xml");
//}
XElement ConvertByteArrayToXml(byte[] data)
{
XmlReaderSettings settings = new XmlReaderSettings();
using (MemoryStream stream = new MemoryStream(data))
using (XmlReader reader = XmlReader.Create(stream, settings))
{
return XElement.Load(reader);
}
}
private byte[] RemoveNulls(byte[] DataStream)
{
for (int i = 0; i < DataStream.Length - 1; i++)
{
if (DataStream[i] == 0x00) DataStream[i] = 0x01;
}
return DataStream;
}
}
}
NetworkStream.Read
返回一个整数,该整数告诉读取的字节数。
你好,我认为我的服务器从TcpClien读取了错误的值。写它应该是52(在我发送时的长度字节数组
不正确。TCP是一种基于流的协议。这意味着TCP可以随心所欲地拆分您的消息。它可以一次发送几个字节,将两条消息合并为一条等等。
因此,您必须在代码中实现某种消息检测。通常有两种方法:
- 引入一个包含消息的字节数的标头
- 在邮件末尾使用分隔符
这是因为您丢弃了有关实际读取字节数的信息,而是使用缓冲区大小。您使用整个缓冲区,尽管它只是部分填充了数据。
Read
方法返回实际从流中读取的字节数。
int bytesRead = networkStream.Read(bytesFrom, 0, bytesFrom.Length);
Console.Write(bytesRead);
此外,您必须重复调用Read
方法,因为它不必一次返回整个流。当流被读取到最后时,Read
方法返回零。
相关:TcpListener随机截断字节数组