Сначала создайте пустое ServerApplication и ClientApplication в качестве консольного приложения, чтобы упростить пример.
Затем поместите определение сериализуемого объекта в отдельную сборку, а затем добавьте ссылку на общую сборку вкаждый проект (сервер и клиент).Требуется совместно использовать один и тот же объект, а не просто копию идентичного класса.
Для создания DLL > Щелкните правой кнопкой мыши в Решение 'ServerApplication' в обозревателе решений.> Добавить новый проект ... -> выбрать библиотеку классов (например, назвать этот проект MySharedHouse ). Переименовать класс Class1 по умолчанию в House и завершить его
[Serializable]
public class House
{
public string Street { get; set; }
public string ZipCode { get; set; }
public int Number { get; set; }
public int Id { get; set; }
public string Town { get; set; }
}
![enter image description here](https://i.stack.imgur.com/ouicN.png)
Щелкните правой кнопкой мыши в MySharedHouse and Build.
Теперь сборка dll собрана, и нам нужно добавить ее в Project Server и Client Project.Щелкните правой кнопкой мыши ServerApplication> Add Reference> Просмотрите и найдите dll, для этого примера
Projects \ ServerApplication \ MySharedHouse \ bin \ Debug \ MySharedHouse.dll
Повторитепроцесс в ClientApplication с использованием того же самого dll (тот же путь).
Теперь вы можете использовать экземпляры класса House в ServerApplication и ClientApplication в качестве единого объекта, просто добавив предложение "using MySharedHouse" вверх.
КОД СЕРВЕРА
using System;
using System.Net;
using System.Net.Sockets;
using System.Runtime.Serialization.Formatters.Binary;
using System.Threading;
using MySharedHouse;
namespace ServerApplication
{
class Program
{
static void Main(string[] args)
{
MessageServer s = new MessageServer(515);
s.Start();
}
}
public class MessageServer
{
private int _port;
private TcpListener _tcpListener;
private bool _running;
private TcpClient connectedTcpClient;
private BinaryFormatter _bFormatter;
private Thread _connectionThread;
public MessageServer(int port)
{
this._port = port;
this._tcpListener = new TcpListener(IPAddress.Loopback, port);
this._bFormatter = new BinaryFormatter();
}
public void Start()
{
if (!_running)
{
this._tcpListener.Start();
Console.WriteLine("Waiting for a connection... ");
this._running = true;
this._connectionThread = new Thread
(new ThreadStart(ListenForClientConnections));
this._connectionThread.Start();
}
}
public void Stop()
{
if (this._running)
{
this._tcpListener.Stop();
this._running = false;
}
}
private void ListenForClientConnections()
{
while (this._running)
{
this.connectedTcpClient = this._tcpListener.AcceptTcpClient();
Console.WriteLine("Connected!");
House house = new House();
house.Street = "Evergreen Terrace";
house.ZipCode = "71474";
house.Number = 742;
house.Id = 34527;
house.Town = "Springfield";
_bFormatter.Serialize(this.connectedTcpClient.GetStream(), house);
Console.WriteLine("send House!");
}
}
}
}
КОД КЛИЕНТА
using System;
using System.Net.Sockets;
using System.Runtime.Serialization.Formatters.Binary;
using System.Threading;
using MySharedHouse;
namespace ClientApplication
{
class Program
{
static void Main(string[] args)
{
MessageClient client = new MessageClient(515);
client.StartListening();
}
}
public class MessageClient
{
private int _port;
private TcpClient _tcpClient;
private BinaryFormatter _bFormatter;
private Thread _listenThread;
private bool _running;
private House house;
public MessageClient(int port)
{
this._port = port;
this._tcpClient = new TcpClient("127.0.0.1", port);
this._bFormatter = new BinaryFormatter();
this._running = false;
}
public void StartListening()
{
lock (this)
{
if (!_running)
{
this._running = true;
this._listenThread = new Thread
(new ThreadStart(ListenForMessage));
this._listenThread.Start();
}
else
{
this._running = true;
this._listenThread = new Thread
(new ThreadStart(ListenForMessage));
this._listenThread.Start();
}
}
}
private void ListenForMessage()
{
Console.WriteLine("Reading...");
try
{
while (this._running)
{
this.house = (House)this._bFormatter.Deserialize(this._tcpClient.GetStream());
Console.WriteLine(this.house.Street);
Console.WriteLine(this.house.ZipCode);
Console.WriteLine(this.house.Number);
Console.WriteLine(this.house.Id);
Console.WriteLine(this.house.Town);
}
}
catch (Exception e)
{
Console.WriteLine(e);
Console.ReadLine();
}
}
}
}
Wooala!первый дом для отправки по TCP / IP