Socket/ServerSYNC/Program.cs

76 lines
2.4 KiB
C#

using System;
using System.Net;
using System.Net.Sockets;
using System.Text;
namespace ServerSYNC
{
class Program
{
// Data recibida desde el cliente
public static string data = null;
static void Main(string[] args)
{
StartListening();
}
public static void StartListening() {
// Arreglo como buffer de la data recibida del cliente
byte[] bytes = new Byte[1024];
// Se definen las variables del Host ip, puerto
// Al usar esto la IP es 127.0.0.1
//IPHostEntry ipHostInfo = Dns.GetHostEntry(Dns.GetHostName());
//IPAddress ipAddress = ipHostInfo.AddressList[0];
// Se define la IP explicitamente
IPAddress ipAddress = IPAddress.Parse("192.168.0.20");
IPEndPoint localEndPoint = new IPEndPoint(ipAddress, 11000);
// Se crea el socket de tipo TCP/IP sobre el puerto 11000.
Socket listener = new Socket(ipAddress.AddressFamily,
SocketType.Stream, ProtocolType.Tcp );
// Se inicia el socket y queda a la escucha
try {
listener.Bind(localEndPoint);
listener.Listen(10);
while (true) {
Console.WriteLine("Esperando datos del Cliente...");
// El programa se suspende mientras espera una conexión entrante.
Socket handler = listener.Accept();
data = null;
// Una conexión entrante necesita ser procesada.
while (true) {
int bytesRec = handler.Receive(bytes);
data += Encoding.ASCII.GetString(bytes,0,bytesRec);
if (data.IndexOf("<EOF>") > -1) {
break;
}
}
Console.WriteLine( "Data Recivida desde el Cliente : {0}", data);
// Se devuelven datos al cliente.
byte[] msg = Encoding.ASCII.GetBytes(data);
handler.Send(msg);
handler.Shutdown(SocketShutdown.Both);
handler.Close();
}
} catch (Exception e) {
Console.WriteLine(e.ToString());
}
Console.WriteLine("\n Fin...");
Console.Read();
}
}
}