public static void StartListener() { // Buffer para datos entrantes. byte[] bytes = new Byte[1024]; // Establecemos dirección local del socket. // // IPHostEntry ipHostInfo = Dns.Resolve("localhost"); IPAddress ipAddress = ipHostInfo.AddressList[0]; //El servidor correrá en el puerto 12 IPEndPoint localEndPoint = new IPEndPoint(ipAddress, 12); // Creamos un TCP/IP socket. Socket listener = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); // Enlazar el socket a la dirección especificada antes (localEndPoint) y escuchar por conexiones entrantes. try { listener.Bind(localEndPoint); listener.Listen(100); while (true) { // Set el evento a nonsignaled state. allDone.Reset(); // IMPORTANTE: AQUÍ ES DONDE LANZAMOS EL SOCKET DE FORMA ASÍNCRONA A LA ESPERA DE RECIBIR CONEXIONES ENTRANTES. log.EscribirEnLog("El servidor está esperando conexiones..."); listener.BeginAccept( new AsyncCallback(AcceptCallback), listener); // Esperar hasta que una conexión sea hecha antes de continuar. allDone.WaitOne(); } } catch (Exception e) { log.EscribirEnLog("Error al intentar enlazar el socket a la dirección: " + e.ToString()); } //Console.WriteLine("\nPress ENTER to continue..."); //Console.Read(); }
public void lanzarHiloServidor() { CLog log = new CLog(); try { hiloServidor = new Thread(StartListener); hiloServidor.Start(); while (!hiloServidor.IsAlive) { log.EscribirEnLog("No arranco el servidor (StartListener()),reintentamos"); System.Threading.Thread.Sleep(5000); } log.EscribirEnLog("Servidor arrancado"); } catch (Exception e) { log.EscribirEnLog("Error lanzando servidor (lanzarHiloServidor)" + e.Message); } }
/// <summary> /// Botón para arrancar el servicio servidor. Envía petición de este inicio a la clase 'server' para arrancar dicho servicio. /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void button1_Click(object sender, EventArgs e) { //ConfiguracionINI ini = new ConfiguracionINI(); //ini.getValorParametro(); //Cargamos en variables los datos necesarios para conexion (ip y puerto) CLog log = new CLog(); try { WindowsFormsApplication1.clases.Chat.clases.CreateListener servidor = new WindowsFormsApplication1.clases.Chat.clases.CreateListener(); servidor.lanzarHiloServidor(); } catch (Exception error) { log.EscribirEnLog(error.Message); } }