CLX C++ Libraries
Home >> tcp::socket

Declarations

namespace tcp {
    template <int Family>
    class basic_socket : public basic_rawsocket<SOCK_STREAM, Family, 0>;
    
    typedef basic_socket<AF_INET> socket;
    typedef basic_sockaddress<AF_INET, IPPROTO_TCP> sockaddress;
    typedef basic_acceptor<AFINET> acceptor;
    typedef basic_sockbuf<socket> sockbuf;
    typedef basic_sockstream<socket> sockstream;
    typedef basic_sockmanager<SOCK_STREAM, AF_INET, 0> sockmanager;
};

Overview

tcp::socket は,サーバ/クライアント型モデルで TCP による通信を行う際に使用するソケットを生成するためのクラスです.tcp::socket は, サーバへ接続要求を送信して TCP コネクションを確立するまでの作業を担います. その後の実際のデータ転送は,tcp::sockstream(詳細は sockstreamを参照)を用いて行います.

Example

example_tcp_client.cpp

#include <iostream>
#include <string>
#include <cstdlib>
#include <cstring>
#include "clx/tcp.h"

int main(int argc, char* argv[]) {
    if (argc < 3) std::exit(-1);
    
    try {
        clx::tcp::socket s;
        s.connect(host, clx::tcp::port(argv[2]));
        clx::tcp::sockstream tcps(s);
        
        while (1) {
            std::string buf;
            std::cin >> buf;
            if (std::cin.eof()) break;
            tcps << buf;
        }
        s.close();
    }
    catch (clx::socket_error& e) {
        std::cerr << e.what() << std::endl;
        std::exit(-1);
    }
    catch (clx::sockaddress_error& e) {
        std::cerr << e.what() << std::endl;
        std::exit(-1);
    }
    
    return 0;
}

サーバ側のサンプルプログラムについては,tcp::acceptor を参照して下さい (example_tcp_server.cpp).

Template Parameters

Family
プロトコルファミリーを指定します.

Related Types

typedef basic_rawsocket<SOCK_STREAM, Family> rawsocket;
typedef basic_sockaddress<Family, IPPROTO_TCP> sockaddress;
typedef char char_type;
typedef typename std::basic_string<char> string_type;

Construction and Member Functions

basic_socket();
basic_socket(const basic_socket& cp);
explicit basic_socket(soket_int s, const sockaddress& addr);
explicit basic_socket(const char_type* host, int port);
explicit basic_socket(const string_type& host, int port);
virtual ~basic_socket();

basic_socket& connect(const char_type* host, int port);
basic_socket& connect(const string_type& host, int port);

bool is_connect() const;
const sockaddress& address() const;

int send(const char_type* src, int n);
int send(const string_type& src);
int recv(char_type* src, int n);

Related Pages

  1. CLX C++ Libraries - tcp::acceptor
  2. CLX C++ Libraries - sockstream