Programación de sockets en C#

La programación de sockets es una forma de conectar dos Nodes en una red para comunicarse entre sí. Básicamente, es una configuración unidireccional de Cliente y Servidor en la que un Cliente se conecta, envía mensajes al servidor y el servidor los muestra mediante una conexión de socket. Un socket (Node) escucha en un puerto particular en una IP, mientras que otro socket se comunica con el otro para formar una conexión. El servidor forma el socket de escucha mientras el cliente se comunica con el servidor. Antes de profundizar en el código del servidor y el cliente, se recomienda encarecidamente pasar por el modelo TCP/IP .
 

Programación del lado del cliente

  Antes de crear el socket del cliente, un usuario debe decidir a qué ‘ Dirección IP ‘ desea conectarse, en este caso, es el host local . Al mismo tiempo, también necesitamos el método ‘ Familia ‘ que pertenecerá al propio socket. Luego, a través del método ‘ conectar ‘, conectaremos el socket al servidor. Antes de enviar cualquier mensaje, debe convertirse en una array de bytes. Entonces, y solo entonces, se puede enviar al servidor a través del método ‘ enviar ‘. Más tarde, gracias al método ‘ recibir ‘, obtendremos una array de bytes como respuesta del servidor. Es de destacar que, al igual que en el lenguaje C, los métodos ‘enviar’ y ‘recibir’ aún devuelven la cantidad de bytes enviados o recibidos.

C#

// A C# program for Client
using System;
using System.Net;
using System.Net.Sockets;
using System.Text;
 
namespace Client {
 
class Program {
 
// Main Method
static void Main(string[] args)
{
    ExecuteClient();
}
 
// ExecuteClient() Method
static void ExecuteClient()
{
 
    try {
         
        // Establish the remote endpoint
        // for the socket. This example
        // uses port 11111 on the local
        // computer.
        IPHostEntry ipHost = Dns.GetHostEntry(Dns.GetHostName());
        IPAddress ipAddr = ipHost.AddressList[0];
        IPEndPoint localEndPoint = new IPEndPoint(ipAddr, 11111);
 
        // Creation TCP/IP Socket using
        // Socket Class Constructor
        Socket sender = new Socket(ipAddr.AddressFamily,
                   SocketType.Stream, ProtocolType.Tcp);
 
        try {
             
            // Connect Socket to the remote
            // endpoint using method Connect()
            sender.Connect(localEndPoint);
 
            // We print EndPoint information
            // that we are connected
            Console.WriteLine("Socket connected to -> {0} ",
                          sender.RemoteEndPoint.ToString());
 
            // Creation of message that
            // we will send to Server
            byte[] messageSent = Encoding.ASCII.GetBytes("Test Client<EOF>");
            int byteSent = sender.Send(messageSent);
 
            // Data buffer
            byte[] messageReceived = new byte[1024];
 
            // We receive the message using
            // the method Receive(). This
            // method returns number of bytes
            // received, that we'll use to
            // convert them to string
            int byteRecv = sender.Receive(messageReceived);
            Console.WriteLine("Message from Server -> {0}",
                  Encoding.ASCII.GetString(messageReceived,
                                             0, byteRecv));
 
            // Close Socket using
            // the method Close()
            sender.Shutdown(SocketShutdown.Both);
            sender.Close();
        }
         
        // Manage of Socket's Exceptions
        catch (ArgumentNullException ane) {
             
            Console.WriteLine("ArgumentNullException : {0}", ane.ToString());
        }
         
        catch (SocketException se) {
             
            Console.WriteLine("SocketException : {0}", se.ToString());
        }
         
        catch (Exception e) {
            Console.WriteLine("Unexpected exception : {0}", e.ToString());
        }
    }
     
    catch (Exception e) {
         
        Console.WriteLine(e.ToString());
    }
}
}
}
Programación del lado del servidor

De la misma manera, necesitamos una ‘dirección IP’ que identifique el servidor para permitir que los clientes se conecten. Después de crear el socket, llamamos al método ‘ bind ‘ que vincula la IP al socket. Luego, llame al método ‘ escuchar ‘. Esta operación es responsable de crear la cola de espera que estará relacionada con cada ‘ socket ‘ abierto. El método ‘ escucha ‘ toma como entrada el número máximo de clientes que pueden permanecer en la cola de espera. Como se indicó anteriormente, existe comunicación con el cliente a través de métodos de  ‘ envío ‘ y ‘ recepción ‘.

Nota: No olvide la conversión en una array de bytes. 

C#

// A C# Program for Server
using System;
using System.Net;
using System.Net.Sockets;
using System.Text;
 
namespace Server {
 
class Program {
 
// Main Method
static void Main(string[] args)
{
    ExecuteServer();
}
 
public static void ExecuteServer()
{
    // Establish the local endpoint
    // for the socket. Dns.GetHostName
    // returns the name of the host
    // running the application.
    IPHostEntry ipHost = Dns.GetHostEntry(Dns.GetHostName());
    IPAddress ipAddr = ipHost.AddressList[0];
    IPEndPoint localEndPoint = new IPEndPoint(ipAddr, 11111);
 
    // Creation TCP/IP Socket using
    // Socket Class Constructor
    Socket listener = new Socket(ipAddr.AddressFamily,
                 SocketType.Stream, ProtocolType.Tcp);
 
    try {
         
        // Using Bind() method we associate a
        // network address to the Server Socket
        // All client that will connect to this
        // Server Socket must know this network
        // Address
        listener.Bind(localEndPoint);
 
        // Using Listen() method we create
        // the Client list that will want
        // to connect to Server
        listener.Listen(10);
 
        while (true) {
             
            Console.WriteLine("Waiting connection ... ");
 
            // Suspend while waiting for
            // incoming connection Using
            // Accept() method the server
            // will accept connection of client
            Socket clientSocket = listener.Accept();
 
            // Data buffer
            byte[] bytes = new Byte[1024];
            string data = null;
 
            while (true) {
 
                int numByte = clientSocket.Receive(bytes);
                 
                data += Encoding.ASCII.GetString(bytes,
                                           0, numByte);
                                            
                if (data.IndexOf("<EOF>") > -1)
                    break;
            }
 
            Console.WriteLine("Text received -> {0} ", data);
            byte[] message = Encoding.ASCII.GetBytes("Test Server");
 
            // Send a message to Client
            // using Send() method
            clientSocket.Send(message);
 
            // Close client Socket using the
            // Close() method. After closing,
            // we can use the closed Socket
            // for a new Client Connection
            clientSocket.Shutdown(SocketShutdown.Both);
            clientSocket.Close();
        }
    }
     
    catch (Exception e) {
        Console.WriteLine(e.ToString());
    }
}
}
}

Para ejecutar en Terminal o Símbolo del sistema: 

  • Primero guarde los archivos con la extensión .cs. Supongamos que guardamos los archivos como client.cs y server.cs .
  • Luego compile ambos archivos ejecutando los siguientes comandos:
$ csc client.cs
$ csc server.cs
  • Después de una compilación exitosa, abra los dos cmd, uno para el servidor y otro para el cliente, y primero intente ejecutar el servidor de la siguiente manera

  • Después de eso, en otro cmd, ejecute el código del cliente y vea el siguiente resultado en el cmd del lado del servidor.

  • Ahora puede ver los cambios en el servidor tan pronto como se ejecuta el programa cliente.

Publicación traducida automáticamente

Artículo escrito por GiovanniDezio y traducido por Barcelona Geeks. The original can be accessed here. Licence: CCBY-SA

Deja una respuesta

Tu dirección de correo electrónico no será publicada. Los campos obligatorios están marcados con *