void ReceiveMessages() { try { byte[] infoBytes = new byte[8]; server.Receive(infoBytes); var info = TransferInfo.FromBytes(infoBytes); byte[] buffer = new byte[250]; MemoryStream memoryStream = new MemoryStream(); int left = info.Size; int count = 0; while (left > 0) { int download = left < buffer.Length ? left : buffer.Length; count = server.Receive(buffer, download, SocketFlags.None); memoryStream.Write(buffer, 0, count); left -= count; } switch (info.Type) { case (MessageType.GetAnswer): reciveAnswer = Encoding.UTF8.GetString(memoryStream.ToArray()); break; } } catch { MessageBox.Show("Connection with server is lost"); } }
//зєднання клієнта void ConnectClient(User client) { try { while (true) { byte[] infoBytes = new byte[8]; client.SocketUser.Receive(infoBytes); var info = TransferInfo.FromBytes(infoBytes); byte[] buffer = new byte[250]; MemoryStream memoryStream = new MemoryStream(); int left = info.Size; int count = 0; while (left > 0) { int download = left < buffer.Length ? left : buffer.Length; count = client.SocketUser.Receive(buffer, download, SocketFlags.None); memoryStream.Write(buffer, 0, count); left -= count; } string recive = Encoding.UTF8.GetString(memoryStream.ToArray()); FunctionForSwich(info, recive, client); } } catch (SocketException se) { client.SocketUser.Shutdown(SocketShutdown.Both); client.SocketUser.Close(); //users.Remove(client); //string error = se.Message; //labelListError.Text += $"{error}\n"; MessageBox.Show(se.Message); } }
//отримання повідомлення void ReceiveMessages() { try { while (true) { byte[] infoBytes = new byte[8]; server.Receive(infoBytes); var info = TransferInfo.FromBytes(infoBytes); byte[] buffer = new byte[250]; MemoryStream memoryStream = new MemoryStream(); int left = info.Size; int count = 0; while (left > 0) { int download = left < buffer.Length ? left : buffer.Length; count = server.Receive(buffer, download, SocketFlags.None); memoryStream.Write(buffer, 0, count); left -= count; } string recive = Encoding.UTF8.GetString(memoryStream.ToArray()); switch (info.Type) { case MessageType.Test: { var serializer = new XmlSerializer(typeof(MakeTest)); //MakeTest desr; using (TextReader reader = new StringReader(recive)) { test = (MakeTest)serializer.Deserialize(reader); } Dispatcher.Invoke(() => { mainWindow.Children.Clear(); FillFild(); FillRadioAnswer(); FillQuestions(); EndExamButton.IsEnabled = true; }); break; } case MessageType.SendMark: { Dispatcher.Invoke(() => { YourMark.Text = recive; }); break; } case MessageType.Error: { System.Windows.MessageBox.Show("Uppss some error"); break; } } } } catch (Exception ex) { System.Windows.MessageBox.Show(ex.Message); System.Windows.MessageBox.Show("Connection with server is lost"); } }