Created
July 26, 2015 14:59
-
-
Save Fhernd/239d14fa4bff9d4012e9 to your computer and use it in GitHub Desktop.
Servidor y cliente para demostración de uso de named pipes.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// OrtizOL - xCSw - http://ortizol.blogspot.com | |
using System; | |
using System.IO; | |
using System.IO.Pipes; | |
namespace Receta.CSharp.R0526 | |
{ | |
public class ServidorClienteNamedPipe | |
{ | |
public static void Main(string[] args) | |
{ | |
Console.WriteLine(Environment.NewLine); | |
// Valida el modo de conexión (servidor o cliente): | |
if (args.Length > 0 && args[0] == "cliente") | |
{ | |
IniciarClientePipe(); | |
} | |
else | |
{ | |
IniciarServidorPipe(); | |
} | |
Console.WriteLine(Environment.NewLine); | |
} | |
private static void IniciarServidorPipe() | |
{ | |
// Creación del servidor: | |
NamedPipeServerStream servidor = new NamedPipeServerStream("servidor"); | |
// A espera de conexiones: | |
Console.WriteLine ("Esperando una conexión..."); | |
servidor.WaitForConnection(); | |
Console.WriteLine ("Conexión establecida con un cliente."); | |
// Asocia un objeto StreamWriter y StreamReader con el servidor para | |
// envío y recepción de datos: | |
StreamReader sr = new StreamReader(servidor); | |
StreamWriter sw = new StreamWriter(servidor); | |
// Envío de datos: | |
for(int i = 1; i <= 10; ++i) | |
{ | |
Console.WriteLine ("[SERVIDOR]> Enviando dato: {0}", i.ToString()); | |
sw.WriteLine("Dato: {0}", i.ToString()); | |
sw.Flush(); | |
} | |
// Recepción de datos: | |
for (int i = 1; i <= 10; ++i) | |
{ | |
Console.WriteLine ("[SERVIDOR]> Dato recibido: {0}", sr.ReadLine()); | |
} | |
// Cierra el servidor: | |
servidor.Close(); | |
} | |
private static void IniciarClientePipe() | |
{ | |
// Creación del cliente: | |
NamedPipeClientStream cliente = new NamedPipeClientStream("servidor"); | |
// Conexión con el servidor: | |
cliente.Connect(); | |
// Asocia un objeto StreamWriter y StreamReader con el cliente para | |
// envío y recepción de datos: | |
StreamReader sr = new StreamReader(cliente); | |
StreamWriter sw = new StreamWriter(cliente); | |
// Recepción de datos: | |
for (int i = 1; i <= 10; ++i) | |
{ | |
Console.WriteLine ("[CLIENTE]> Dato recibido: {0}", sr.ReadLine()); | |
} | |
// Envío de datos: | |
for (int i = 1; i <= 10; ++i) | |
{ | |
Console.WriteLine ("[CLIENTE]> Enviando dato: {0}", i.ToString()); | |
sw.WriteLine("Dato: {0}", i.ToString()); | |
sw.Flush(); | |
} | |
// Cierre del cliente: | |
cliente.Close(); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment