server.cpp 2.0 KB
Newer Older
X
xwhqsj 已提交
1 2 3 4 5 6 7
#include <unistd.h>
#include <cstdio>
#include <sys/socket.h>
#include <cstdlib>
#include <netinet/in.h>
#include <cstring>
#include <iostream>
X
xwhqsj 已提交
8
#include <vector>
X
xwhqsj 已提交
9 10 11

#define PORT 8080

X
xwhqsj 已提交
12 13
int main(int argc, char const *argv[])
{
X
xwhqsj 已提交
14 15 16 17 18 19 20 21 22
    int server_fd, new_socket, valread;
    struct sockaddr_in address;

    int opt = 1;
    int addrlen = sizeof(address);
    char buffer[1024] = {0};
    char *hello = "Hello from server";

    // Creating socket file descriptor
X
xwhqsj 已提交
23 24
    if ((server_fd = socket(AF_INET, SOCK_STREAM, 0)) == 0)
    {
X
xwhqsj 已提交
25 26 27 28 29 30
        perror("socket failed");
        exit(EXIT_FAILURE);
    }

    // Forcefully attaching socket to the port 8080
    if (setsockopt(server_fd, SOL_SOCKET, SO_REUSEADDR | SO_REUSEPORT,
X
xwhqsj 已提交
31 32
                   &opt, sizeof(opt)))
    {
X
xwhqsj 已提交
33 34 35 36 37
        perror("setsockopt");
        exit(EXIT_FAILURE);
    }
    address.sin_family = AF_INET;
    address.sin_addr.s_addr = INADDR_ANY;
X
xwhqsj 已提交
38
    address.sin_port = htons( PORT );
X
xwhqsj 已提交
39 40

    // Forcefully attaching socket to the port 8080
X
xwhqsj 已提交
41 42 43
    if (bind(server_fd, (struct sockaddr *)&address,
             sizeof(address))<0)
    {
X
xwhqsj 已提交
44 45 46
        perror("bind failed");
        exit(EXIT_FAILURE);
    }
X
xwhqsj 已提交
47 48
    if (listen(server_fd, 3) < 0)
    {
X
xwhqsj 已提交
49 50 51
        perror("listen");
        exit(EXIT_FAILURE);
    }
X
xwhqsj 已提交
52 53 54
    if ((new_socket = accept(server_fd, (struct sockaddr *)&address,
                             (socklen_t*)&addrlen))<0)
    {
X
xwhqsj 已提交
55 56 57 58
        perror("accept");
        exit(EXIT_FAILURE);
    }

X
xwhqsj 已提交
59 60
    valread = read( new_socket , buffer, 1024);
    printf("%s\n",buffer );
X
xwhqsj 已提交
61

X
xwhqsj 已提交
62 63 64 65 66 67 68 69 70 71 72 73 74
    send(new_socket , hello , strlen(hello) , 0 );
    printf("Hello message sent\n");

    char* psql;
    char* dbn;
    char delims[] = "$";
    char *res = nullptr;
    std::vector<char*> resvec;

    printf("%zu\n", strlen(buffer));

    res = strtok(buffer, delims);
    while (res != nullptr)
X
xwhqsj 已提交
75
    {
X
xwhqsj 已提交
76 77
        resvec.push_back(res);
        res = strtok(nullptr, delims);
X
xwhqsj 已提交
78
    }
X
xwhqsj 已提交
79 80 81

    psql = resvec[0];
    dbn = resvec[1];
X
xwhqsj 已提交
82 83 84 85 86
    printf("%s\n", psql);
    printf("%s\n", dbn);

    return 0;
}