Created
November 6, 2020 22:44
-
-
Save BaezCrdrm/60870d10349434ac0ee033a5ad261b52 to your computer and use it in GitHub Desktop.
Ejemplo de servidor sencillo TCP
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
using System; | |
using System.Net; | |
using System.Net.Sockets; | |
using System.Text; | |
namespace SocketCom | |
{ | |
public class ServidorTCP | |
{ | |
public TcpListener escucha { get; set; } | |
public bool aceptar { get; private set; } | |
public ServidorTCP(string ip, int puerto, bool start = false) | |
{ | |
IPAddress direccion = IPAddress.Parse(ip); | |
this.escucha = new TcpListener(direccion, puerto); | |
if(start == true) | |
{ | |
escucha.Start(); | |
Console.WriteLine("Servidor iniciado en la dirección {0}:{1}", | |
direccion.MapToIPv4().ToString(), puerto.ToString()); | |
aceptar = true; | |
} | |
} | |
public void Escuchar() | |
{ | |
if(escucha != null && aceptar == true) | |
{ | |
while(true) | |
{ | |
Console.WriteLine("Esperando conexión de cliente..."); | |
var clientTask = escucha.AcceptSocketAsync(); | |
if(clientTask.Result != null) | |
{ | |
Console.WriteLine("Cliente conectado. Esperando datos"); | |
var client = clientTask.Result; | |
string msg = ""; | |
while(msg != null && !msg.StartsWith("salir")) | |
{ | |
byte[] data = Encoding.UTF8.GetBytes("Envía datos. Envía \"salir\" para terminar"); | |
client.Send(data); | |
byte[] buffer = new byte[1024]; | |
client.Receive(buffer); | |
msg = Encoding.ASCII.GetString(buffer); | |
Console.WriteLine(msg); | |
} | |
Console.WriteLine("Cerrando conexión"); | |
client.Dispose(); | |
} | |
} | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment