自己封裝的乙個 TCP 套接字基類

2021-05-22 09:13:28 字數 2017 閱讀 5115

tcpsocket.h

#ifndef __ctcpsocket_h__

#define __ctcpsocket_h__

#include

enum oper_type ;

enum send_error_type ;

#define buffer_size 4096

class ctcpsocket

oper_type   getopertype( void )          

unsigned long  getipaddr( void )          

char*    getip( void )           

socket    getsocket( void )          

sockaddr_in*  getsockaddr( void )          };

#endif

tcpsocket.cpp

#include "tcpsocket.h"

#include

#include

ctcpsocket::ctcpsocket( void )

ctcpsocket::~ctcpsocket( void )

releasesocket(); }

void ctcpsocket::recvdata( void ) 

unsigned long  flag=0;

dword recvbyte;

bool ctcpsocket::senddata( char* pbuf, dword dwlength ) 

if( null == pbuf ) 

if(dwlength > buffer_size ) 

m_wsasendbuf.buf = m_szsendbuf;

m_wsasendbuf.len = dwlength;

m_dwopertype = send_posted;

int nerr = ::wsagetlasterror();

if( ( socket_error == nret ) && ( wsa_io_pending != nerr ) )

else }

void ctcpsocket::initsocket( socket s, sockaddr_in* psockaddr )

void ctcpsocket::releasesocket( void )

linger lingerstruct;

lingerstruct.l_onoff=1;

lingerstruct.l_linger=0;

setsockopt( m_socket, sol_socket, so_linger, ( char*)&lingerstruct, sizeof( lingerstruct ) );

shutdown( m_socket, sd_both );

closesocket( m_socket );

m_socket = invalid_socket; 

m_nneterr = 0;

m_ulipaddr = 0;

memset( m_szip, 0, buffer_size );

memset( &m_sockaddr, 0, sizeof( sockaddr_in ) );}

m_sockaddr.sin_addr.s_un.s_addr = inet_addr( pdestaddr ) ;

m_sockaddr.sin_family = af_inet ;

m_sockaddr.sin_port = htons( nport ) ;

int nret = ::wsaconnect( m_socket, ( sockaddr* )&m_sockaddr, sizeof( sockaddr ),0, 0, 0, 0 );

if ( socket_error == nret ) 

return true;

}

乙個簡單的TCP套接字程式設計例項

採用乙個伺服器程式對應乙個客戶的方法,伺服器不需要採取任何併發技術,執行tcp套接字服務端的基本過程是建立套接字,繫結套接字,監聽,接收請求,讀 寫資料和終止連線。伺服器源程式 include include include include include include include inclu...

自己封裝的乙個MySQL類

import pymysql import logging 獲取logger的例項 logger logging.getlogger lzjf 指定logger的輸出格式 formatter logging.formatter asctime s levelname s message s 檔案日誌...

使用socketserver寫乙個套接字程式

使用socketserver寫乙個套接字程式來實現多執行緒,即伺服器端可與多個客戶端進行通話,首先伺服器端程式為 usr bin python coding utf 8 import socketserver class mytcphandle socketserver.baserequesthan...