TcpClient.Read从TcpClient.Write读取错误的值?

时间:2012-03-15 10:47:22

标签: c#

您好我认为我的服务器从TcpClien.Write读取错误的值它应该是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;
        }
    }
}

2 个答案:

答案 0 :(得分:3)

NetworkStream.Read返回一个整数,表示读取的字节数。

  

您好我认为我的服务器从TcpClien.Write读取错误的值它应该是52(我发送它时的长度字节数组

不正确的。 TCP是基于流的协议。这意味着TCP可以根据需要拆分您的消息。它可以一次发送几个字节,将两条消息合并为一个等等。

因此,您必须在代码中实现某种消息检测。通常使用两种方式:

  1. 引入包含消息
  2. 的字节数的标头
  3. 在邮件末尾使用分隔符

答案 1 :(得分:1)

那是因为你丢弃了有关读取的实际字节数的信息,而是使用缓冲区大小。您使用整个缓冲区,尽管它只是部分填充了数据。

Read方法返回实际从流中读取的字节数。

int bytesRead = networkStream.Read(bytesFrom, 0, bytesFrom.Length);
Console.Write(bytesRead);

此外,您必须重复调用Read方法,因为它不必一次返回整个流。当流被读到末尾时,Read方法返回零。

相关:TcpListener truncating byte array randomly