Invertir una string en C/C++ usando el modelo de servidor cliente

Este artículo describe una configuración de Cliente y Servidor en la que un Cliente se conecta, envía una string al servidor y el servidor muestra la string original y envía una string invertida al cliente mediante una conexión de socket.

Prerrequisito: Programación de sockets

Ejemplos:

Input : welcome
Output :emoclew

Input :geeks for geeks
Output :skeeg rof skeeg

Explicación
En esto, primero configure la conexión cliente-servidor. Cuando se establezca la conexión, el cliente enviará la string de entrada del usuario al servidor mediante una llamada al sistema de envío. En el lado del servidor, el servidor esperará la string enviada por el cliente. String de lectura del servidor por llamada al sistema de lectura. Después de esto, el servidor invertirá la string y la enviará de vuelta al cliente.

Compilación:
1. Primero ejecute el programa del servidor como

gcc Server.c -o server

2. Ejecute el programa cliente en otro terminal

gcc Client.c -o client

3. El programa del servidor está esperando la string enviada por el cliente.
4. Ingrese la string en el lado del cliente.
5. El programa del servidor imprimirá la string original.
6. El programa cliente imprimirá una string invertida.

Cliente.c

C

// C client code to send string to reverse
#include <arpa/inet.h>
#include <netinet/in.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/socket.h>
#include <unistd.h>
  
#define PORT 8090
  
// Driver code
int main()
{
    struct sockaddr_in address;
    int sock = 0, valread;
    struct sockaddr_in serv_addr;
    char str[100];
  
    printf("\nInput the string:");
    scanf("%[^\n]s", str);
  
    char buffer[1024] = { 0 };
  
    // Creating socket file descriptor
    if ((sock = socket(AF_INET,
                       SOCK_STREAM, 0))
        < 0) {
        printf("\n Socket creation error \n");
        return -1;
    }
  
    memset(&serv_addr, '0', sizeof(serv_addr));
    serv_addr.sin_family = AF_INET;
    serv_addr.sin_port = htons(PORT);
  
    // Convert IPv4 and IPv6 addresses from
    // text to binary form 127.0.0.1 is local
    // host IP address, this address should be
    // your system local host IP address
    if (inet_pton(AF_INET, "127.0.0.1",
                  &serv_addr.sin_addr)
        <= 0) {
        printf("\nAddress not supported \n");
        return -1;
    }
  
    // connect the socket
    if (connect(sock, (struct sockaddr*)&serv_addr,
                sizeof(serv_addr))
        < 0) {
        printf("\nConnection Failed \n");
        return -1;
    }
  
    int l = strlen(str);
  
    // send string to server side
    send(sock, str, sizeof(str), 0);
  
    // read string sent by server
    valread = read(sock, str, l);
  
    printf("%s\n", str);
  
    return 0;
}

Servidor.c

C

// Server C code to reverse a
// string by sent from client
#include <netinet/in.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/socket.h>
#include <unistd.h>
  
#define PORT 8090
  
// Driver code
int main()
{
    int server_fd, new_socket, valread;
    struct sockaddr_in address;
    char str[100];
    int addrlen = sizeof(address);
    char buffer[1024] = { 0 };
    char* hello = "Hello from server";
  
    // Creating socket file descriptor
    if ((server_fd = socket(AF_INET, 
                          SOCK_STREAM, 0)) == 0) {
        perror("socket failed");
        exit(EXIT_FAILURE);
    }
  
    address.sin_family = AF_INET;
    address.sin_addr.s_addr = INADDR_ANY;
    address.sin_port = htons(PORT);
  
    // Forcefully attaching socket to
    // the port 8090
    if (bind(server_fd, (struct sockaddr*)&address, 
                          sizeof(address)) < 0) {
        perror("bind failed");
        exit(EXIT_FAILURE);
    }
  
    // puts the server socket in passive mode
    if (listen(server_fd, 3) < 0) {
        perror("listen");
        exit(EXIT_FAILURE);
    }
    if ((new_socket = accept(server_fd,
                  (struct sockaddr*)&address,
                  (socklen_t*)&addrlen)) < 0) {
        perror("accept");
        exit(EXIT_FAILURE);
    }
  
    // read string send by client
    valread = read(new_socket, str,
                   sizeof(str));
    int i, j, temp;
    int l = strlen(str);
  
    printf("\nString sent by client:%s\n", str);
  
    // loop to reverse the string
    for (i = 0, j = l - 1; i < j; i++, j--) {
        temp = str[i];
        str[i] = str[j];
        str[j] = temp;
    }
  
    // send reversed string to client
    // by send system call
    send(new_socket, str, sizeof(str), 0);
    printf("\nModified string sent to client\n");
  
    return 0;
}

Publicación traducida automáticamente

Artículo escrito por spartan_mnnit 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 *