To begin with, I'm a student, don't scold me too much for my code, I'm trying to get better. I will accept any criticism about the code, it helps to get better)
The crux of my problem: when the server is disconnected, I send a command to it, process it, and send a response from the server stating that it has completed its work, in my second project (client) I receive a message and process it, and sometimes it is processed, and sometimes it happens the problem is that I just get an exception. And it comes out of nothing, the server shutdown function works, I have to display a MessageBox, and it immediately switches me to another function and receives an exception for converting a byte to an object (the function works correctly, all other commands work without problems). I have already climbed all the Internet resources, nothing helps.
Where does the exception occur
public Object ByteArrayToObject(byte[] arrBytes)
{
using (var memStream = new MemoryStream())
{
var binForm = new BinaryFormatter();
memStream.Write(arrBytes, 0, arrBytes.Length);
memStream.Seek(0, SeekOrigin.Begin);
object obj = binForm.Deserialize(memStream);***//ERROR HERE System.Runtime.Serialization.SerializationException: The input stream is not a valid binary format. The starting contents (in bytes) are:***
return obj;
}
}
The start of an exception occurs in this function after receiving a message from the server before or during the display of the MessageBox at this moment it switches me to this function and catches an exception
private void DisconnectServer()
{
try
{
string theMessage = "Клиент выполнил дисконнект";
byte[] msg = Encoding.Default.GetBytes(theMessage);
int bytesSent = sock.Send(msg);
byte[] bytes = new byte[1024];
int bytesRec = sock.Receive(bytes);
string msgserv = Encoding.Default.GetString(bytes, 0, bytesRec);
//MessageBox.Show("Сервер (" + sock.RemoteEndPoint.ToString() + ") ответил: " + msgserv);
sock.Shutdown(SocketShutdown.Both);
sock.Close();
}
catch (Exception ex)
{
MessageBox.Show("Клиент: " + ex.Message);
}
}
The moment the server message is sent to the client about the disconnection and after which an error occurs
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine(client + ":" + data);
Console.ResetColor();
string theReply = "Сервер остановлен";
byte[] msg = Encoding.Default.GetBytes(theReply);
handler.Send(msg);
choice = 0;
handler.Shutdown(SocketShutdown.Both);
handler.Close();
break;