Сериализация объекта класса и передача его по TCP - C#
Формулировка задачи:
Отредактировал найденный пример из сети, но при работе клиента выбивает ошибку: Необработанное исключение типа ссылая на formatter.Serialize(strm, p);
Клиент:
Листинг программы
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Text;
- using System.IO;
- using System.Net;
- using System.Net.Sockets;
- using System.Runtime.Serialization;
- using System.Runtime.Serialization.Formatters.Binary;
- namespace ClientTcp
- {
- class Program
- {
- class Person
- {
- public string FirstName;
- public string LastName;
- public int age;
- public Person(string i, string s, int k)
- {
- FirstName = i;
- LastName = s;
- age = k;
- }
- }
- public static void Main()
- {
- try
- {
- string serverIp = "127.0.0.1";
- Int32 port = 9050;
- Person p = new Person("Иван", "Иванов", 20);
- TcpClient client = new TcpClient(serverIp, port);
- IFormatter formatter = new BinaryFormatter(); // Модуль форматирования, который будет сериализовать класс
- NetworkStream strm = client.GetStream(); // поток
- formatter.Serialize(strm, p); // процесс сериализации
- strm.Close();
- client.Close();
- }
- catch (ArgumentNullException e)
- {
- Console.WriteLine("ArgumentNullException: {0}", e);
- }
- catch (SocketException e)
- {
- Console.WriteLine("SocketException: {0}", e);
- }
- Console.WriteLine("\nНажмите enter для продолжения...");
- Console.Read();
- }
- }
- }
Сервер:
Листинг программы
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Text;
- using System.IO;
- using System.Net;
- using System.Net.Sockets;
- using System.Runtime.Serialization;
- using System.Runtime.Serialization.Formatters.Binary;
- namespace TcpServer
- {
- class Programm
- {
- class Person
- {
- public string FirstName;
- public string LastName;
- public int age;
- public Person(string i, string s, int k)
- {
- FirstName = i;
- LastName = s;
- age = k;
- }
- }
- public static void Main()
- {
- try
- {
- TcpListener server = new TcpListener(9050);
- server.Start();
- TcpClient client = server.AcceptTcpClient();
- NetworkStream strm = client.GetStream();
- IFormatter formatter = new BinaryFormatter();
- Person p = (Person)formatter.Deserialize(strm);
- Console.WriteLine("Меня зовут: " + p.FirstName + " " + p.LastName + " и мне " + p.age);
- strm.Close();
- client.Close();
- server.Stop();
- }
- catch (ArgumentNullException e)
- {
- Console.WriteLine("ArgumentNullException: {0}", e);
- }
- catch (SocketException e)
- {
- Console.WriteLine("SocketException: {0}", e);
- }
- Console.WriteLine("\nНажмите enter для продолжения...");
- Console.Read();
- }
- }
- }
Решение задачи: «Сериализация объекта класса и передача его по TCP»
textual
Листинг программы
- bool isServer = Console.ReadLine() == "s";
- if (isServer)
- Server();
- else
- Client();
ИИ поможет Вам:
- решить любую задачу по программированию
- объяснить код
- расставить комментарии в коде
- и т.д