【发布时间】:2015-07-07 17:13:41
【问题描述】:
您好,我在使用这段代码时遇到了一些问题:
这个:
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); 收到以下错误:
在 mscorlib.dll 中发生了“System.Runtime.Serialization.SerializationException”类型的未处理异常 附加信息:输入流不是有效的二进制格式。起始内容(以字节为单位)为:35-2D-33-39-61-30-63-65-33-65-37-38-33-65-05-FB-FF ...
我不知道我做错了什么......
有人可以帮帮我吗?
非常感谢您的宝贵时间!
---- 编辑----
服务器.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());
}
}
}
数据包.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
}
}
客户端.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; }
}
}
【问题讨论】:
-
你能贴出 p.ToBytes() 的代码吗?如果它没有以与反序列化相同的方式序列化,您将收到此错误。
-
是的,您应该使用
BinaryFormatter来生成要发送的字节数组。 -
Packet.cs是在客户端和服务器之间共享的 DLL 中,还是您将代码复制到每个中? -
@Sidewinder94 不,你不应该,
BinaryFormatter不打算用于机器对机器通信或持久存储。它的唯一用途是在同一台机器上的进程之间进行 IPC。这是极不容忍变化的,如果您在线路的两侧没有完全相同的二进制文件,您通常无法对数据进行反序列化。请改用 ProtoBuff-net 之类的第 3 方格式化程序。
标签: c# serialization stream binary byte