Skip to content

cpyberry/socketpp

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

68 Commits
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

socketpp

Simple and modern socket library for C++

Requirement

  • C++17

Usage

When the server receives the message {1, 2, 3, 4, 5} from the client and then sends the message {1, 2, 3, 4, 5} to the client.

For example, We set the IP address and port of server and client as follows.

std::string_view server_ip = "0.0.0.0";
std::uint16_t server_port = 50000;

std::string_view client_ip = "0.0.0.0";
std::uint16_t client_port = 50000;

// data to send to each other
std::vector<char> data = {1, 2, 3, 4, 5};

// buffer size when sending and receiving
int size = 1024

TCP server

#include <array>
#include <iostream>
#include <string_view>
#include <cstdint>
#include <vector>

#include "winsock2.h"

#include "socketpp.hpp"


socketpp::Socket server(PF_INET, SOCK_STREAM);
server.bind(server_ip, server_port);
server.setsockopt(SOL_SOCKET, SO_REUSEADDR, true);
server.listen(1);
auto [client, address] = server.accept();

// client ip address and port
std::cout << address.ip_address() << std::endl;
std::cout << address.port() << std::endl;

std::array<char, size> recved_data = client.recv<size>();
int sended_size = client.send(data);

client.close();

TCP client

socketpp::Socket sock(PF_INET, SOCK_STREAM);
sock.bind("0.0.0.0", 50000);
sock.setsockopt(SOL_SOCKET, SO_REUSEADDR, true);
sock.connect(server_ip, server_port);

sock.send(data);
sock.recv<size>();

sock.close();

UDP server

socketpp::Socket server(PF_INET, SOCK_STREAM);
server.bind(server_ip, server_port);
server.setsockopt(SOL_SOCKET, SO_REUSEADDR, true);

const auto [buffer, address] = server.recv_from<size>();

// The next two lines have the same meaning.
//server.sendto(data, client_ip, client_port);
server.sendto(data, address);

server.close();

UDP client

socketpp::Socket sock(PF_INET, SOCK_STREAM);
sock.bind(client_ip, client_port);
sock.setsockopt(SOL_SOCKET, SO_REUSEADDR, true);

sock.sendto(data, server_ip, server_port);
sock.recv_from<size>();

sock.close();

Founder