Выполнение программы Linux C ++ в Windows

0

Я видел, что некоторые из файлов заголовков c++ в Windows имеют альтернативу в Linux. Здесь я создал программу сокетов и еще одну программу обработки строк в linux - c++.

Можно ли изменить так, что тот же код работает как в Windows, так и в Linux?

код 1:

#include <fcntl.h>
#include <string.h>
#include <stdlib.h>
#include <errno.h>
#include <stdio.h>
#include <netinet/in.h>
#include <resolv.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <unistd.h>
//#include <sstream.h>
#include <pthread.h>                        
#include <iostream>
#include <sstream>
#include <cstdio>
#include <vector>
#include <map>
#include "dictionary_exclude.h"
#pragma GCC diagnostic ignored "-Wwrite-strings"

void *SocketHandler(void *);

int main(int argv, char **argc)
{
    int host_port = 1103;
    char buf[20];
    int k;
    struct sockaddr_in my_addr;
    int hsock;
    int *p_int;
    int err;
    socklen_t addr_size = 0;
    int *csock;
    sockaddr_in sadr;
    pthread_t thread_id = 0;

    hsock = socket(AF_INET, SOCK_STREAM, 0);
    if (hsock == -1) {
    printf("Error initializing socket %dn", errno);
    goto FINISH;
    }

    p_int = (int *) malloc(sizeof(int));
    *p_int = 1;

    if ((setsockopt(hsock, SOL_SOCKET, SO_REUSEADDR, (char *) p_int, sizeof(int)) == -1) || (setsockopt(hsock, SOL_SOCKET, SO_KEEPALIVE, (char *) p_int, sizeof(int)) == -1)) {
    printf("Error setting options %dn", errno);
    free(p_int);
    goto FINISH;
        }
    free(p_int);

    my_addr.sin_family = AF_INET;
    my_addr.sin_port = htons(host_port);

    memset(&(my_addr.sin_zero), 0, 8);
    my_addr.sin_addr.s_addr = INADDR_ANY;

    if (bind(hsock, (sockaddr *) & my_addr, sizeof(my_addr)) == -1) {
    fprintf(stderr, "Error binding to socket, make sure nothing else is listening on this port %dn", errno);
    goto FINISH;
    }
    if (listen(hsock, 10) == -1) {
    fprintf(stderr, "Error listening %dn", errno);
    goto FINISH;
    }
    //Now lets do the server stuff

    addr_size = sizeof(sockaddr_in);

    while (true) {
    printf("waiting for a connectionn\n");
    csock = (int *) malloc(sizeof(int));
    if ((*csock = accept(hsock, (sockaddr *) & sadr, &addr_size)) != -1) {
        printf("---------------------nReceived connection from %s\n", inet_ntoa(sadr.sin_addr));
        pthread_create(&thread_id, 0, &SocketHandler, (void *) csock); //Pthread to manage requests from multiple clients
        pthread_detach(thread_id);
    } else {
        fprintf(stderr, "Error accepting %dn", errno);
    }
    }

  FINISH:
    ;
}

void *SocketHandler(void *lp)
{
    int ar[10];
    int result=0;
    int *csock = (int *) lp;
    char buf[20];
    int k;

    const unsigned int MAX_BUF_LENGTH = 4096;
    std::vector<char> buffer(MAX_BUF_LENGTH);
    std::string input;   
    int bytesReceived = 0;

    //char buffer[1024];
    int buffer_len = 1024;
    int bytecount;

    int i = 0;
    std::string current;
    std::vector<std::string> sentences;

    if ((bytecount = recv(*csock, (char*) input.c_str(), input.length(), 0)) == -1) { 
    fprintf(stderr, "Error receiving data %d \n", errno);
    goto FINISH;
    }    

                do {
        bytesReceived = recv(*csock, buffer.data(), buffer.size(), 0);
        // append string from buffer.

        if ( bytesReceived == -1 ) 
        { 
            fprintf(stderr, "Error receiving data %d \n", errno);
        goto FINISH;
    } 
    else 
            input.append( buffer.cbegin(), buffer.cend() );         

    } while ( bytesReceived == MAX_BUF_LENGTH );  

    while(i < input.length())
    {
        current += input[i];
        if(input[i] == '"')
        {
            int j = i + 1;
            while( j < input.length() && input[j] != '"')
            {
                current += input[j];
                j ++;
            }
            current += input[j];
            i = j + 1;
        }

        if(input[i] == '.' || input [i] == '!' || input[i] == '?')
        {
            sentences.push_back(current);
            current = "";
        }
        i ++;
    }

    for(i =0; i<sentences.size(); i++)
    {
        std::cout << i << " -> " << sentences[i] << std::endl;
    }



    if ((bytecount = send(*csock, (char *)ar, i *sizeof(int), 0)) == -1) { // Here we cant send lenth-1. It consider exact
    fprintf(stderr, "Error sending data %d\n", errno);
    goto FINISH;
    }

  FINISH:
    free(csock);
    return 0;
}

код 2:

#include<stdio.h>
#include<string.h>
#include "client.h"
int main(int argc, char *argv[] )
{
    const char *buffer;
    const char *ch;
    std::string input = argv[1];
    int ar[2];
    printf("Client : \n");
    if ( argc != 2 ) /* argc should be 2 for correct execution */
    {
              printf( "\n%s filename\n", argv[0] );
    }
    else 
    {       

    ch=client(input);
    ar[0]=((int*)ch)[0];
    ar[1]=((int*)ch)[1];

    }

    printf("\n @ar[0]=%d;ar[1]=%d@ \n",ar[0],ar[1]);
    return ar[1];
}

файл заголовка

#include <iostream>
#ifndef client_h__
#define client_h__
extern char *client(std::string string_input);

#endif
  • 0
    Да, это работает, я портировал код сокетов раньше. Просто используйте ifdef, чтобы получить текущую ОС. Если вы хотите примеры / полный код, просто спросите.
  • 0
    Вы также можете использовать Boost для кроссплатформенной разработки.
Показать ещё 3 комментария
Теги:
visual-c++

1 ответ

2

Сокеты и потоки не имеют стандартного API, используемого как для Windows, так и для Linux. Хотя они несколько похожи, вам придется изменить свой код, чтобы заставить его работать для окон.

  • 0
    Так что один и тот же код сокета не может быть использован как в Windows, так и в Linux, верно?
  • 0
    Нет. Для Windows Socket API требуются дополнительные примитивные вызовы (например, WSAStartup). Для обзора, смотрите: msdn.microsoft.com/en-us/library/windows/desktop/…

Ещё вопросы

Сообщество Overcoder
Наверх
Меню