输入流不是有效的二进制格式。序列化问题

时间:2015-04-28 17:46:36

标签: c# serialization stream binary byte

您好,我对这段代码有些问题:

此:

public void SendRegistrationPacket()
    {
        Packet p = new Packet(PacketType.Registration, "server");
        p.Gdata.Add(id);
        clientSocket.Send(p.ToBytes());
    }

向此发送p.ToBytes()

public Packet(byte[] packetbytes)
    {
        BinaryFormatter bf = new BinaryFormatter();
        MemoryStream ms = new MemoryStream(packetbytes);
        Packet p = (Packet)bf.Deserialize(ms);
        ms.Close();
        this.Gdata = p.Gdata;
        this.packetInt = p.packetInt;
        this.packetBool = p.packetBool;
        this.senderID = p.senderID;
        this.packetType = p.packetType;
    }

我在Packet p = (Packet)bf.Deserialize(ms);发现了以下错误:

  

未处理的类型' System.Runtime.Serialization.SerializationException'发生在mscorlib.dll中   附加信息:输入流不是有效的二进制格式。起始内容(以字节为单位)为:35-2D-33-39-61-30-63-65-33-65-37-38-33-65-05-FB-FF ...

我不知道我做错了什么......

有人可以帮助我吗?

非常感谢你的时间!

----编辑----

Server.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using ServerData;
using System.Net.Sockets;
using System.IO;
using System.Threading;
using System.Net;
using Newtonsoft.Json;
using Server;

namespace Server
{
    class Server
    {

        static Socket listenerSocket;
        static List<ClientData> clients;

        static void Main(string[] args)
        {

            Console.WriteLine("Starting Server On: " + Packet.GetIP4Address());
            listenerSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            clients = new List<ClientData>();

            IPEndPoint ip = new IPEndPoint(IPAddress.Parse(Packet.GetIP4Address()), 4242);

            listenerSocket.Bind(ip);

            Thread listenThread = new Thread(ListenThread);
            listenThread.Start();

        } //Start server


        //Listner - listens for clients trying to connect
        static void ListenThread()
        {
            while (true)
            {
                listenerSocket.Listen(0);

                clients.Add(new ClientData(listenerSocket.Accept()));

            }
        }

        //ClientData thread - receives data from each client individually
        public static void Data_IN(object cSocket)
        {
            Socket clientSocket = (Socket)cSocket;
            byte[] buffer;
            int readBytes;
            while (true)
            {
                try
                {

                    buffer = new byte[clientSocket.SendBufferSize];
                    readBytes = clientSocket.Receive(buffer);

                    if (readBytes > 0)
                    {
                        //handle data
                        Packet packet = new Packet(buffer);
                        DataManger(packet);
                    }
                }
                catch (SocketException ex)
                {
                    //Console.WriteLine("A Client Had Disconnected!");
                }
            }
        }

        //Data Manager
        public static void DataManger(Packet p)
        {
            switch (p.packetType)
            {
                case PacketType.Chat:
                    foreach (ClientData c in clients)
                    {
                        c.clientSocket.Send(p.ToBytes());
                    }
                    break;
                case PacketType.Connect:
                    //Console.WriteLine("User: \"" + p.Gdata[0] + "\" Has connected from IP: " + p.Gdata[1]);

                    string response = System.IO.File.ReadAllText(@"D:\json.txt");//"{\"one\": \"0\",\"two\": \"45\",\"three\": \"5\",\"four\": \"86\",\"five\": \"75\",\"six\": \"32\",\"Count\": \"6883197667\"}";

                    response = response.Substring(1, response.Length - 2);

                    Rootobject root = JsonConvert.DeserializeObject<Rootobject>(response);

                    foreach (ClientData c in clients)
                    {
                        if (c.id == p.Gdata[1])
                        {
                            Packet packet = new Packet(PacketType.Message, "Server");
                            packet.Gdata.Add(root.one);
                            packet.Gdata.Add(root.two);
                            packet.Gdata.Add(root.three);
                            packet.Gdata.Add(root.four);
                            packet.Gdata.Add(root.five);
                            packet.Gdata.Add(root.six);
                            packet.Gdata.Add(root.Count);
                            packet.Gdata.Add(root.Found);
                            c.clientSocket.Send(packet.ToBytes());
                            break;
                        }
                    }

                    break;
                case PacketType.Message:

                    List<Rootobject> data = new List<Rootobject>();

                    data.Add(
                        new Rootobject
                        {
                            one = p.Gdata[0],
                            two = p.Gdata[1],
                            three = p.Gdata[2],
                            four = p.Gdata[3],
                            five = p.Gdata[4],
                            six = p.Gdata[5],
                            Count = p.Gdata[6],
                            Found = p.Gdata[7]
                        }
                        );

                    string json = JsonConvert.SerializeObject(data.ToArray());

                    System.IO.File.WriteAllText(@"D:\json.txt", json);

                    string responseB = System.IO.File.ReadAllText(@"D:\json.txt");

                    responseB = responseB.Substring(1, responseB.Length -2);

                    Rootobject rootB = JsonConvert.DeserializeObject<Rootobject>(responseB);

                    foreach (ClientData c in clients)
                    {
                        if (c.id == p.Gdata[8])
                        {
                            Packet packet = new Packet(PacketType.Message, "Server");
                            packet.Gdata.Add(rootB.one);
                            packet.Gdata.Add(rootB.two);
                            packet.Gdata.Add(rootB.three);
                            packet.Gdata.Add(rootB.four);
                            packet.Gdata.Add(rootB.five);
                            packet.Gdata.Add(rootB.six);
                            packet.Gdata.Add(rootB.Count);
                            packet.Gdata.Add(rootB.Found);
                            c.clientSocket.Send(packet.ToBytes());
                            break;
                        }
                    }

                    break;
                case PacketType.Disconnect:
                    Console.WriteLine("User: \"" + p.Gdata[0] + "\" Has disconnected from IP: " + p.Gdata[1]);
                    break;
            }
        }



    }
}

ClientData.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Net.Sockets;
using System.IO;
using System.Threading;
using ServerData;
using System.Runtime.Serialization.Formatters.Binary;

namespace Server
{
    class ClientData
    {

        public Socket clientSocket;
        public Thread clientThread;
        public string id;

        public ClientData()
        {
            id = Guid.NewGuid().ToString();
            clientThread = new Thread(Server.Data_IN);
            clientThread.Start(clientSocket);
            SendRegistrationPacket();
        }
        public ClientData(Socket clientSocket)
        {
            this.clientSocket = clientSocket;
            id = Guid.NewGuid().ToString();
            clientThread = new Thread(Server.Data_IN);
            clientThread.Start(clientSocket);
            SendRegistrationPacket();
        }

        public void SendRegistrationPacket()
        {
            //Packet p = new Packet(PacketType.Registration, "server");
            //p.Gdata.Add(id);
            ////clientSocket.Send(p.ToBytes());
            //BinaryFormatter bf = new BinaryFormatter();
            //MemoryStream ms = new MemoryStream();

            Packet p = new Packet(PacketType.Registration, "server");
            p.Gdata.Add(id);

            BinaryFormatter bf = new BinaryFormatter();
            MemoryStream ms = new MemoryStream();
            bf.Serialize(ms, p);
            clientSocket.Send(ms.ToArray());
        }
    }
}

Packet.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using ServerData;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;
using System.Net;

namespace ServerData
{
    [Serializable]
    public class Packet
    {
        public List<string> Gdata;
        public int packetInt;
        public bool packetBool;
        public string senderID;
        public PacketType packetType;

        public Packet(PacketType type, string senderID)
        {
            Gdata = new List<string>();
            this.senderID = senderID;
            this.packetType = type;
        }

        public Packet(byte[] packetbytes)
        {
            BinaryFormatter bf = new BinaryFormatter();
            MemoryStream ms = new MemoryStream(packetbytes);
            Packet p = (Packet)bf.Deserialize(ms);
            ms.Close();
            this.Gdata = p.Gdata;
            this.packetInt = p.packetInt;
            this.packetBool = p.packetBool;
            this.senderID = p.senderID;
            this.packetType = p.packetType;
        }

        public byte[] ToBytes()
        {
            BinaryFormatter bf = new BinaryFormatter();
            MemoryStream ms = new MemoryStream();

            bf.Serialize(ms, this);

            byte[] bytes = ms.ToArray();
            ms.Close();

            return bytes;
        }

        public static string GetIP4Address()
        {
            IPAddress[] ips = Dns.GetHostAddresses(Dns.GetHostName());

            foreach (IPAddress ip in ips)
            {
                if (ip.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork)
                {
                    return ip.ToString();
                }
            }

            return "127.0.0.1";
        }

    }

    public enum PacketType
    {
        Registration,
        Chat,
        Connect,
        Disconnect,
        Message
    }
}

Client.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using ServerData;
using System.Net;
using System.Net.Sockets;
using System.IO;
using System.Threading;
using System.Security.Cryptography;

namespace Client
{
    class Client
    {
        public static Socket master;
        public static string id;

        #region MD5 Crack vars
        public static bool found = false;
        public static string charsS = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQESTUVWXYZ0123456789~!@#$%^&*_-+=`|\\(){}[]:;\"'<>,.?/ëÿüïöäêÛîôâéýúíóáé";
        public static int length = 6;
        public static int threadCountInt = 1;
        public static int[] count;
        public static long counter = 0;
        public static long counterS = 0;
        public static string test = "";
        public static char[] chars;
        public static DateTime start;
        public static int threadCount = 0;
        public static List<string> threads = new List<string>();
        public static string result;
        public static string[] currentA;
        public static Object thisLock = new Object();
       // public static IniFile ini;
        public static long runtime;
        public static string current;
        #endregion

        static void Main(string[] args)
        {
            Console.Write("Number of threads to run: ");
            threadCountInt = int.Parse(Console.ReadLine());
            chars = charsS.ToArray();
            start = DateTime.Now;
            currentA = new string[threadCountInt];

            count = new int[length];

            while (true)
            {
                Console.Clear();
                Console.Write("Enter Host IP Address: ");
                string ip = Console.ReadLine();

                master = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

                IPEndPoint ipe = new IPEndPoint(IPAddress.Parse(ip), 4242);

                try
                {
                    master.Connect(ipe);
                    Packet p = new Packet(PacketType.Connect, id);
                    p.Gdata.Add(Packet.GetIP4Address());
                    p.Gdata.Add(id);
                    master.Send(p.ToBytes());
                    break;
                }
                catch
                {
                    Console.WriteLine("Could Not Connect To Host!");
                    Thread.Sleep(1000);
                }
            }
            Thread t = new Thread(Data_IN);
            t.Start();

            //Packet packet = new Packet(PacketType.Connect, id);
            //packet.Gdata.Add(Packet.GetIP4Address());
            //packet.Gdata.Add(id);
            //master.Send(packet.ToBytes());

            //while (true)
            //{
            //    Console.Write("::>");
            //    string input = Console.ReadLine();
            //    if (input.ToLower() == "exit" || input.ToLower() == "close")
            //    {
            //        Packet p = new Packet(PacketType.Disconnect, id);
            //        p.Gdata.Add(name);
            //        p.Gdata.Add(Packet.GetIP4Address());
            //        master.Send(p.ToBytes());
            //        Environment.Exit(0);
            //    }
            //    else
            //    {
            //        Packet p = new Packet(PacketType.Chat, id);
            //        p.Gdata.Add(name);
            //        p.Gdata.Add(input);
            //        master.Send(p.ToBytes());
            //    }
            //}

            Thread t2 = new Thread(statusUpdate);
            t2.Start();

            for (int tt = 0; tt < threadCountInt; tt++)
            {
                new Thread(() => work(tt - 1)).Start();
            }

            Console.ReadLine();
            Environment.Exit(0);
            Console.ReadLine();
        }

        static void Data_IN()
        {
            byte[] buffer;
            int readBytes;

            while (true)
            {
                try
                {
                    buffer = new byte[master.SendBufferSize];
                    readBytes = master.Receive(buffer);

                    if (readBytes > 0)
                    {
                        DataManager(new Packet(buffer));
                    }
                }
                catch (SocketException ex)
                {
                    ConsoleColor c = Console.ForegroundColor;
                    Console.ForegroundColor = ConsoleColor.Red;
                    Console.WriteLine("Lost Connection To The Server!");
                    Console.ForegroundColor = c;
                    Console.Write("::>");
                    Console.ReadLine();
                    Environment.Exit(0);
                }
            }
        }

        static void DataManager(Packet p)
        {
            switch (p.packetType)
            {
                case PacketType.Registration:
                    id = p.Gdata[0];
                    break;
                case PacketType.Chat:
                    ConsoleColor c = Console.ForegroundColor;
                    Console.ForegroundColor = ConsoleColor.Cyan;
                    Console.WriteLine(p.Gdata[0] + ": " + p.Gdata[1]);
                    Console.ForegroundColor = c;
                    Console.Write("::>");
                    break;
                case PacketType.Message:
                    count[0] = int.Parse(p.Gdata[0]);
                    count[1] = int.Parse(p.Gdata[1]);
                    count[2] = int.Parse(p.Gdata[2]);
                    count[3] = int.Parse(p.Gdata[3]);
                    count[4] = int.Parse(p.Gdata[4]);
                    count[5] = int.Parse(p.Gdata[5]);
                    counter = long.Parse(p.Gdata[6]);
                    break;
            }
        }

        public static void statusUpdate()
        {
            Thread.Sleep(1000);
            long tmp = 0;
            while (!found)
            {
                Console.Clear();
                Console.WriteLine();
                Console.WriteLine(" " + threadCount.ToString() + " Threads Running");
                Console.Write(" ");
                foreach (string s in threads)
                {
                    if (s != threads[threads.Count - 1])
                    {
                        Console.Write(s + ", ");
                    }
                    else
                    {
                        Console.Write(s);
                    }

                }
                Console.WriteLine();

                Console.WriteLine(" " + (counterS + counter).ToString() + "/" + (long)Math.Pow(charsS.Length, 6) + " (" + ((float)((float)(counterS + counter) / (float)Math.Pow(charsS.Length, 6)) * 100).ToString() + "%)");
                Console.WriteLine(" " + ((long)Math.Pow(charsS.Length, 6) - counter).ToString() + " Left");

                if (counter > 0 && TimeSpanInSecs(start) > 0)
                {
                    tmp = (counter / TimeSpanInSecs(start));
                }
                else
                {
                    tmp = 0;
                }

                Console.WriteLine(" " + tmp.ToString() + " H/S");
                if (tmp > 0)
                {
                    long ETA = ((long)Math.Pow(charsS.Length, 6) - (counterS + counter)) / tmp;
                    Console.WriteLine(" " + string.Format("{0:00}:{1:00}:{2:00}", ETA / 3600, (ETA / 60) % 60, ETA % 60) + " ETA");
                }
                else
                {
                    Console.WriteLine(" NaN ETA");
                }

                long totalRun = runtime + TimeSpanInSecs(start);
                Console.WriteLine(" Current Session: " + string.Format("{0:00}:{1:00}:{2:00}", TimeSpanInSecs(start) / 3600, (TimeSpanInSecs(start) / 60) % 60, TimeSpanInSecs(start) % 60));
                Console.WriteLine(" Total Run Time:  " + string.Format("{0:00}:{1:00}:{2:00}", totalRun / 3600, (totalRun / 60) % 60, totalRun % 60));

                Console.WriteLine(" Current: " + current);

                if (found)
                {
                    Console.WriteLine(" Result: " + result);
                }

                Thread.Sleep(1000);
            }
        }

        public static string MD5hasher(string value)
        {
            HashAlgorithm ha = MD5.Create();
            Byte[] cryptedData = ha.ComputeHash(Encoding.UTF8.GetBytes(value));

            StringBuilder sBuilder = new StringBuilder();

            for (int i = 0; i < cryptedData.Length; i++)
            {
                sBuilder.Append(cryptedData[i].ToString("x2"));
            }
            ha.Clear();
            return sBuilder.ToString();
        }

        public static long TimeSpanInSecs(DateTime start)
        {
            TimeSpan tmp = DateTime.Now - start;
            long seconds = tmp.Seconds;
            seconds += tmp.Minutes * 60;
            seconds += (tmp.Hours * 60) * 60;
            seconds += ((tmp.Days * 24) * 60) * 60;

            return seconds;

        }

        public static void work(int Tid)
        {
            int localCount = 0;
            threadCount++;
            threads.Add(Thread.CurrentThread.ManagedThreadId.ToString());
            while (!found)
            {
                test = string.Empty;
                StringBuilder sb = new StringBuilder();
                for (int x = 0; x < length; x++)
                {
                    while (true)
                    {
                        try
                        {
                            sb.Append(chars[count[x]]);
                            break;
                        }
                        catch { }
                    }

                }

                test = sb.ToString();
                current = test;

                count[count.Length - 1] = count[count.Length - 1] + 1;

                for (int y = count.Length; y >= 0; y--)
                {
                    if (y != 0)
                    {
                        if (count[y - 1] >= chars.Length - 1)
                        {
                            if (y > 1)
                            {
                                count[y - 2]++;
                            }
                            count[y - 1] = 0;
                        }
                    }
                    else
                    {
                        if (count[y] == chars.Length - 1)
                        {
                            count[y] = 0;
                        }
                    }

                }

                if (MD5hasher(test) == "de99823d330004610cba3592ce7382b8")
                {
                    result = test;
                    found = true;
                }


                localCount++;

                //lock (thisLock)
                //{
                //    counter += localCount;
                //    localCount = 0;
                //};

                Packet p = new Packet(PacketType.Message, id);
                foreach (int i in count)
                {
                    p.Gdata.Add(i.ToString());
                }
                p.Gdata.Add(localCount.ToString());
                localCount = 0;
                p.Gdata.Add(found.ToString());
                p.Gdata.Add(id);

                master.Send(p.ToBytes());

                if (found)
                {
                    Thread.CurrentThread.Abort();
                }
            }
        }
    }
}

JSON.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Server
{
    public class Rootobject
    {
        public string one { get; set; }
        public string two { get; set; }
        public string three { get; set; }
        public string four { get; set; }
        public string five { get; set; }
        public string six { get; set; }
        public string Count { get; set; }
        public string Found { get; set; }
    }
}

2 个答案:

答案 0 :(得分:3)

问题来自

readBytes = clientSocket.Receive(buffer);

if (readBytes > 0)
{
    //handle data
    Packet packet = new Packet(buffer);
    DataManger(packet);
}

来自客户端的一个发送不等于服务器上的一个接收。您需要“Message Frameing”,您的Packet仅包含已发送数据的第一部分。

最简单的解决方案是首先发送字节数组的长度,然后让接收方只接收该长度,然后分配该大小的缓冲区,直到它完全填充缓冲区为止。

以下是接收方的快速示例

private static byte[] ReadFully(Socket clientSocket, int length)
{
    int offset = 0;
    byte[] buffer = new byte[length];
    while(offset < length)
    {
        int read = clientSocket.Receive(buffer, offset, length - offset, SocketFlags.None);
        if(read = 0)
           return null; //Socket closed
        offset += read;
    }
    return buffer;
}


//read the length
byte[] lengthBuffer = ReadFully(clientSocket, 4);
if(lengthBuffer == null)
{
    //Do something about the closed connection
}
int length = BitConverter.ToInt32(lengthBuffer, 0);

//read the number of bytes specified by the length.
byte[] packetBuffer = ReadFully(clientSocket, length);

if (packetBuffer != null)
{
    //handle data
    Packet packet = new Packet(packetBuffer);
    DataManger(packet);
}

我留给你做派遣方。

答案 1 :(得分:0)

我同意以前的评论者。目前还不清楚你的ToBytes()方法在做什么。你应该做的是这样的事情:

public void SendRegistrationPacket()
    {
        Packet p = new Packet(PacketType.Registration, "server");
        p.Gdata.Add(id);

        BinaryFormatter bf = new BinaryFormatter();
        MemoryStream ms = new MemoryStream();
        bf.Serialize(ms, p);
        clientSocket.Send(ms.ToArray());
    }