Servidor
Código
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Net; using System.Net.Sockets; using System.Runtime.Serialization.Formatters.Binary; using System.IO; namespace TcpServer { class Program { static void Main(string[] args) { //nos ponemos a la escucha tcpListener.Start(); //buffer temporal para recibir data //el encargado de deserializar la data recibida //una lista auxiliar para ir almacenando los bytes while (true) { Console.WriteLine("Esperando data :)"); //acepto la conexión TcpClient tcpClient = tcpListener.AcceptTcpClient(); NetworkStream networkStream = tcpClient.GetStream(); //leo y almaceno en buffer while (networkStream.Read(buffer, 0, buffer.Length) > 0) { //dado que uso el mismo buffer siempre, voy almacenando los bytes en una lista byteList.AddRange(buffer.ToList()); } networkStream.Close(); tcpClient.Close(); //stream auxiliar para luego deserializar { //se deserializa y castea a tipo correcto int[] data = (int[])formatter.Deserialize(memoryStream); //simplemente para mostrar la data foreach (int i in data) { Console.WriteLine("Se recibió el número {0}", i); } } } } } }
Cliente
Código
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Net.Sockets; using System.Runtime.Serialization.Formatters.Binary; using System.Text; using System.Threading.Tasks; namespace tcpClient { class Program { static void Main(string[] args) { //la data que voy a enviar using (NetworkStream networkStream = tcpClient.GetStream()) { { //serializo la data en el stream auxiliar formatter.Serialize(memoryStream, data); byte[] buffer = memoryStream.GetBuffer(); //envio la data networkStream.Write(buffer, 0, buffer.Length); } } tcpClient.Close(); } } }
Lo he comentado, así que espero se entienda
Saludos