65.9K
CodeProject is changing. Read more.
Home

CSyncSocket

starIconstarIcon
emptyStarIcon
starIcon
emptyStarIconemptyStarIcon

2.95/5 (9 votes)

Jun 15, 2005

CPOL
viewsIcon

43762

downloadIcon

1119

A simple TCP class for multithreading usage.

Introduction

First of all, I am sorry for my bad English. CSyncSocket is a simple class that has the same members as CAsyncSocket class, but it can be used in multithreading mode. This class can be used in MFC and Win32 applications. Just include <WINSOCK2.h> and WS2_32.lib in your application and it will work properly.

class CSyncSocket 
{
    public:
    /* close the connection , see ShutDown Method 
    in CAsyncSocket.*/
    void ShutDown(int HOW);
    /* delete any related components for this socket, 
    see CloseSocket Method in CAsynSocket*/
    void Close();
    /* suspend the thread until the queue of the 
    socket get a connection */
    void Accept(CSyncSocket*);
    
    /******************************************************/
    /* attributes */
    /******************************************************/
    /* actes like the Methods in CAsynSocket */
    BOOL GetSockOpt(int nOptionName,void* lpOptionValue,
                  int* lpOptionLen,int nLevel = SOL_SOCKET);
    BOOL SetSockOpt(int nOptionName,const void* lpOptionValue,
                     int nOptionLen,int nLevel = SOL_SOCKET ); 
    /******************************************************/
    /* Operations */
    /******************************************************/
    
    // bind the socket to a port 
    bool Bind(UINT Port);
    // turn the socket into the listen state
    bool Listen(UINT Port);
    // receive an array of bytes of the of size (Length) 
    // and return the actuel data size in the array 
    int Recieve(BYTE*buff, int Length);
    // send an array of bytes of size (Length)
    bool Send(BYTE* buff, int length);
    // connect to a specific host and port 
    bool Connect(LPSTR Host, UINT port);
    
    
    
    /*******************************************************/
    /*// initialization */
    /*******************************************************/
    // create the socket ( for each socket you 
    // must call create anfter the constructor
    BOOL Create();
    CSyncSocket();
    
    
    // operators
    void operator = (CSyncSocket& dest);
    operator SOCKET();
    virtual ~CSyncSocket();
    
    
    //data member 
    SOCKET m_Socket;
    protected:
    virtual bool OnAccept(sockaddr*,int*);
    bool m_IsBound;
    virtual u_long GetCompatibleHost(CString Host);
};