General Socket Wrapper
Go to file
Kirigaya Kazuto 0b13918bc0
Merge pull request #10 from MasterCna/master
added initializer for example
2021-12-18 17:36:28 +08:00
.gitignore Initial Commit 2017-07-27 19:52:58 +08:00
CMakeLists.txt Support cmake (build as a static library) 2018-09-17 18:32:36 +08:00
LICENSE Add MIT License 2018-02-11 15:44:02 +08:00
Readme.md added initializer for example 2021-12-18 12:43:06 +03:30
VERSION Bump version 2018-09-17 22:08:38 +08:00
gsock.cpp NBAcceptResult can stopAtEdge now 2018-09-12 12:43:15 +08:00
gsock.h NBAcceptResult can stopAtEdge now 2018-09-12 12:43:15 +08:00
gsock_helper.cpp sendall now supports string 2018-08-26 00:27:37 +08:00
gsock_helper.h sendall now supports string 2018-08-26 00:27:37 +08:00

Readme.md

General Socket Wrapper

GSOCK is a project created by Kiritow.

Licensed under MIT

Example

TCP Client Example

#include "GSock/gsock.h"
#include "GSock/gsock_helper.h"

int main()
{
    int ret;
    std::string ip;

    // Initiate Socket Handler
    InitNativeSocket();

    if ((ret = DNSResolve("kiritow.com", ip)) < 0)
    {
        printf("Failed to resolve ip address. (%d)\n", ret);
        return 1;
    }
    
    sock s;
    if ((ret = s.connect(ip, 80)) < 0)
    {
        printf("Failed to connect. (%d)\n", ret);
        return 1;
    }

    std::string context("GET / HTTP/1.1\r\nHost: kiritow.com\r\nAccept: */*\r\n\r\n");
    sock_helper sh(s);
    if ((ret=sh.sendall(context.c_str(), context.size())) < 0)
    {
        printf("Failed to send request header. (%d)\n", ret);
        return 1;
    }

    char buff[1024];
    while (true)
    {
        memset(buff, 0, 1024);
        int ret = s.recv(buff, 1024);
        if (ret <= 0) break;
        printf("%s", buff);
    }

    return 0;
}

TCP Echo Server Example

#include "GSock/gsock.h"
#include "GSock/gsock_helper.h"

void service_main(sock& s)
{
    char buff[1024];
    sock_helper sh(s);

    while (true)
    {
        memset(buff, 0, 1024);
        int ret = s.recv(buff, 1024);
        if (ret <= 0) break;
        sh.sendall(buff, ret);
    }
}

int main()
{

    // Initiate Socket Handler
    InitNativeSocket();

    serversock t;
    if (t.bind(59123) < 0 || t.listen(10) < 0)
    {
        printf("Failed to start up server.\n");
        return 1;
    }
    
    while (true)
    {
        sock s;
        if (t.accept(s) < 0)
        {
            printf("Failed to accept.\n");
            break;
        }

        service_main(s);
    }

    return 0;
}