首页 > 解决方案 > 输入流不是有效的二进制格式 Tcp

问题描述

我有两种方法,它们的外观和工作方式非常相似。不知道为什么第一种方法有效,但第二种方法无效。第二次抛出异常“输入流不是有效的二进制格式 Tcp”此方法通过 tcp 将对象从客户端发送到服务器以及从服务器发送到客户端。同一个人可以告诉我我做错了什么吗?

public static void SendComput(NetworkStream stream)
    {

        string id = "1";
        Byte[] datasend = System.Text.Encoding.ASCII.GetBytes(id);

        BinaryFormatter formatter = new BinaryFormatter();
        stream.Write(datasend, 0, datasend.Length);
        Console.WriteLine("Sent: {0}", id);
        while (true)
        {
            try
            {
                var data = new Byte[256];
                String response = String.Empty;
                Int32 bytes = stream.Read(data, 0, data.Length);
                response = System.Text.Encoding.ASCII.GetString(data, 0, bytes);
                Console.WriteLine("Received: {0}", response);
            }
            catch (Exception e)
            {

                throw;
            }

            try
            {
                var t = GetComputeUnitsPerf();
                var t2 = new Comp();
                t2.ComputeTime = (uint)t.TimeMilisceoncd;
                t2.DateCheck = t.Date;
                t2.Id = Int32.Parse(id);
                formatter.Serialize(stream,t2);
                Console.WriteLine("Sent: {0}, {1}, {2}", t2.Id , t2.ComputeTime, t2.DateCheck);
                Thread.Sleep(100);
            }
            catch (Exception e)
            {

                throw;
            }

        }

    }

和服务器:

    public void HandleDeivce3(Object obj)
    {
        TcpClient client = (TcpClient)obj;
        var stream = client.GetStream();
        Byte[] bytes = new Byte[256];
        int i = 0;
        string data = null;

        BinaryFormatter formatter = new BinaryFormatter();
        Task.Run(() =>
        {
            string hex = BitConverter.ToString(bytes);
            data = Encoding.ASCII.GetString(bytes, 0, i);
            Console.WriteLine("Received: {0}", data);

            while (true)
            {
                Thread.Sleep(10000);
                Byte[] reply = System.Text.Encoding.ASCII.GetBytes("Send");
                stream.Write(reply, 0, reply.Length);
                Console.WriteLine("Send");
                Thread.Sleep(200);
                try
                {
                    if (stream.CanRead)
                    {

                        var dataGet = (Comp)formatter.Deserialize(stream);
                        //Console.WriteLine("Sent: {0}, {1}, {2}", dataGet.Id, dataGet.ComputeTime, dataGet.DateCheck);
                        Console.WriteLine(dataGet.Id);
                    }
                }
                catch (Exception e)
                {

                    throw;
                }

            }
        });
    }

我将 [Serializable] 添加到 Comp 类。

标签: c#tcp

解决方案


推荐阅读