Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include "tcp.h"
- namespace tcp
- {
- //struct sock {
- // sock();
- // void (*on_recv)(sock _this, status st);
- // status send( uint8_t *buffer, uint32_t buffer_len, void (*on_sent)(sock _this, status st) );
- // status connect( void (*on_connect)(sock _this, status st) );
- //private:
- // SOCKET s;
- //};
- sock::sock( SOCKET s )
- {
- this->s = s;
- this->on_recv = nullptr;
- }
- sock::sock()
- {
- this->s = SOCKET_ERROR;
- this->on_recv = nullptr;
- }
- status sock::send( uint8_t *buffer, uint32_t buffer_len, void (*on_sent)(sock *_this, status st) )
- {
- std::thread( [buffer, buffer_len, on_sent] (sock *__this, SOCKET s) {
- int r = ::send( s, (const char *)buffer, buffer_len, NULL );
- if ( on_sent )
- on_sent(__this, r != SOCKET_ERROR ? status::OK : status::FAIL );
- }, this, this->s).detach();
- return status::OK;
- }
- status sock::listen( char *address, uint16_t port, void (*on_accept)(sock *_this, status st) )
- {
- int r;
- SOCKET s;
- sockaddr_in name;
- s = socket( AF_INET, SOCK_STREAM, IPPROTO_TCP );
- assert( s != SOCKET_ERROR );
- memset( &name, 0, sizeof(name) );
- name.sin_addr.s_addr = inet_addr( address );
- name.sin_port = htons(port);
- name.sin_family = AF_INET;
- r = bind( s, (sockaddr *)&name, sizeof(name) );
- assert( r != SOCKET_ERROR );
- r = ::listen( s, 64 );
- assert( r != SOCKET_ERROR );
- std::thread( [s, on_accept] () {
- int namelen;
- sockaddr_in name;
- SOCKET con;
- sock sk;
- for (;;) {
- namelen = sizeof(name);
- con = accept( s, (sockaddr *)&name, &namelen );
- assert( con != SOCKET_ERROR );
- sk = sock( con );
- on_accept( &sk, status::OK );
- std::thread( [] (sock sk) {
- int r;
- char buff[1536];
- for (;;) {
- r = recv( sk.s, buff, sizeof(buff), NULL );
- if ( r == 0 ) { // close connection
- if ( sk.on_recv )
- sk.on_recv( &sk, nullptr, r, status::OK );
- return;
- } else if ( r == -1 ) { // error.
- if ( sk.on_recv )
- sk.on_recv( &sk, nullptr, r, status::FAIL );
- return;
- } else { // data
- if ( sk.on_recv )
- sk.on_recv( &sk, (uint8_t *)buff, r, status::OK );
- }
- }
- }, sk).detach();
- }
- }).detach();
- return status::OK;
- }
- };
Add Comment
Please, Sign In to add comment