嘿,伙计们,我正在制作一个聊天程序,我有一个父“MessagePacket”类,其中包含一堆用于发送不同类型数据包的子类,或者包含主聊天窗口的消息,当前聊天的人员列表,私人聊天消息等
在客户端,我做的第一件事是创建一个“AddClientPacket”并将其序列化/发送到服务器,然后服务器将其反序列化为其父“MessagePacket”类,该类包含一个类型属性,用于确定要转换/做什么使用它得到的通用 MessagePacket。
当服务器尝试反序列化它会导致崩溃,我不知道为什么。继承人一些代码:
- 服务器 -
private void HandleClientComm(Object client)
{
Client addClient = new Client(clientIds++, ((TcpClient)client).GetStream());
IFormatter formatter = new BinaryFormatter();
while (true)
{
MessagePacket packet = new MessagePacket();
try
{
packet = (MessagePacket)formatter.Deserialize(addClient.ClientStream);
}
catch (Exception e)
{
MessageBox.Show(e.Message);
}
switch (packet.Type)
{
case MessageType.ALLCHAT:
{
messages.Enqueue(((AllChatPacket)packet).Message);
}
break;
case MessageType.ADDCLIENT:
{
addClient.ClientName = ((AddClientPacket)packet).ClientName;
clientNames.Add(addClient.ClientName);
clientList.Add(addClient);
}
break;
case MessageType.REMOVECLIENT:
{
clientNames.Remove(addClient.ClientName);
clientList.Remove(addClient);
}
break;
case MessageType.PRIVATECHAT:
{
}
break;
}
}
}
- 客户 -
public void ListenToServer()
{
AddClientPacket addClient = new AddClientPacket();
addClient.Type = MessageType.ADDCLIENT;
name = addClient.ClientName = Interaction.InputBox("Whats your name", "Name?", "", 100, 100);
try
{
formatter.Serialize(clientStream, addClient);
}
catch (Exception e)
{
MessageBox.Show(e.Message);
this.Close();
return;
}
while (true)
{
if (quit)
{
break;
}
MessagePacket packet = new MessagePacket();
try
{
packet = (MessagePacket)formatter.Deserialize(clientStream);
}
catch (Exception)
{
return;
}
switch (packet.Type)
{
case MessageType.ALLCHAT:
{
textBox1.Text = textBox1.Text + Environment.NewLine + ((AllChatPacket)packet).Message;
textBox1.Refresh();
}
break;
case MessageType.NAMELIST:
{
clientNameList.DataSource = ((NameListPacket)packet).ClientNames;
}
break;
}
}
}