C++网络编程

Posted on 2007-12-23 21:46 Lemo 阅读(684) 评论(1)  编辑 收藏 引用

头文件SOCKETLIBSOCKET_H

#ifndef SOCKETLIBSOCKET_H
#define SOCKETLIBSOCKET_H
#include "BasicLib/BasicLib.h"
#include "SocketLibTypes.h"
#include "SocketLibErrors.h"
namespace SocketLib
{
class Socket
    {
    public:

        inline sock GetSock() const
        {
            return m_sock;
        }


        inline port GetLocalPort() const
        {
            return ntohs( m_localinfo.sin_port );
        }

        inline ipaddress GetLocalAddress() const
        {
            return m_localinfo.sin_addr.s_addr;
        }


        void Close();


        void SetBlocking( bool p_blockmode );

 

    protected:

        Socket( sock p_socket = -1 );


        sock m_sock;                  

        struct sockaddr_in m_localinfo;

        bool m_isblocking;        
    };

 

    class DataSocket : public Socket
    {
    public:

        DataSocket( sock p_socket = -1 );

 
        inline ipaddress GetRemoteAddress() const
        {
            return m_remoteinfo.sin_addr.s_addr;
        }


 
        inline port GetRemotePort() const
        {
            return ntohs( m_remoteinfo.sin_port );
        }

 

        inline bool IsConnected() const
        {
            return m_connected;
        }

 

        void Connect( ipaddress p_addr, port p_port );


        int Send( const char* p_buffer, int p_size );

  
        int Receive( char* p_buffer, int p_size );

   
        void Close();

    protected:

        bool m_connected;             

        struct sockaddr_in m_remoteinfo;

    };

 

    class ListeningSocket : public Socket
    {
    public:

 
        ListeningSocket();

 
        void Listen( port p_port );


        DataSocket Accept();

 
        inline bool IsListening() const
        {
            return m_listening;
        }


 
        void Close();

    protected:
        bool m_listening;           

    };


}  


#endif

//Cpp文件

#include "SocketLibSocket.h"

namespace SocketLib
{

    void Socket::Close()
    {

    #ifdef WIN32
        closesocket( m_sock );
    #else
        close( m_sock );
    #endif


        m_sock = -1;
    }

    void Socket::SetBlocking( bool p_blockmode )
    {
        int err;

        #ifdef WIN32
            unsigned long mode = !p_blockmode;
            err = ioctlsocket( m_sock, FIONBIO, &mode );
        #else
 
            int flags = fcntl( m_sock, F_GETFL, 0 );

 
            if( p_blockmode == false )
            {
                flags |= O_NONBLOCK;
            }
            else
            {
                flags &= ~O_NONBLOCK;
            }
            err = fcntl( m_sock, F_SETFL, flags );
        #endif

        if( err == -1 )
        {
            throw( Exception( GetError() ) );
        }

        m_isblocking = p_blockmode;
    }


    Socket::Socket( sock p_socket )
    : m_sock( p_socket )
    {
        if( p_socket != -1 )
        {
            socklen_t s = sizeof(m_localinfo);
            getsockname( p_socket, (sockaddr*)(&m_localinfo), &s );
        }


        m_isblocking = true;
    }

 


    DataSocket::DataSocket( sock p_socket )
    : Socket( p_socket ),
    m_connected( false )
    {
        if( p_socket != -1 )
        {
            socklen_t s = sizeof(m_remoteinfo);
            getpeername( p_socket, (sockaddr*)(&m_remoteinfo), &s );
            m_connected = true;
        }
    }


    void DataSocket::Connect( ipaddress p_addr, port p_port )
    {
        int err;

        if( m_connected == true )
        {
            throw Exception( EAlreadyConnected );
        }

        if( m_sock == -1 )
        {
            m_sock = socket( AF_INET, SOCK_STREAM, IPPROTO_TCP );

            if( m_sock == -1 )
            {
                throw Exception( GetError() );
            }
        }


        m_remoteinfo.sin_family = AF_INET;
        m_remoteinfo.sin_port = htons( p_port );
        m_remoteinfo.sin_addr.s_addr = p_addr;
        memset( &(m_remoteinfo.sin_zero), 0, 8 );

        socklen_t s = sizeof(struct sockaddr);
        err = connect( m_sock, (struct sockaddr*)(&m_remoteinfo), s );
        if( err == -1 )
        {
            throw Exception( GetError() );
        }

        m_connected = true;

        err = getsockname( m_sock, (struct sockaddr*)(&m_localinfo), &s );
        if( err != 0 )
        {
            throw Exception( GetError() );
        }
    }

    int DataSocket::Send( const char* p_buffer, int p_size )
    {
        int err;

        if( m_connected == false )
        {
            throw Exception( ENotConnected );
        }

        err = send( m_sock, p_buffer, p_size, 0 );
        if( err == -1 )
        {
            Error e = GetError();
            if( e != EOperationWouldBlock )
            {
                throw Exception( e );
            }
            err = 0;
        }
        return err;
    }
    int DataSocket::Receive( char* p_buffer, int p_size )
    {
        int err;

        if( m_connected == false )
        {
            throw Exception( ENotConnected );
        }
        err = recv( m_sock, p_buffer, p_size, 0 );
        if( err == 0 )
        {
            throw Exception( EConnectionClosed );
        }
        if( err == -1 )
        {
            throw Exception( GetError() );
        }

        return err;
    }

    void DataSocket::Close()
    {
        if( m_connected == true )
        {
            shutdown( m_sock, 2 );
        }

        Socket::Close();

        m_connected = false;
    }

    ListeningSocket::ListeningSocket()
    {
        m_listening = false;
    }
    void ListeningSocket::Listen( port p_port )
    {
        int err;
        if( m_sock == -1 )
        {
            m_sock = socket( AF_INET, SOCK_STREAM, IPPROTO_TCP );
            if( m_sock == -1 )
            {
                throw Exception( GetError() );
            }
        }

        int reuse = 1;
        err = setsockopt( m_sock, SOL_SOCKET, SO_REUSEADDR,
                          (char*)(&reuse), sizeof( reuse ) );
        if( err != 0 )
        {
            throw Exception( GetError() );
        }

        m_localinfo.sin_family = AF_INET;
        m_localinfo.sin_port = htons( p_port );
        m_localinfo.sin_addr.s_addr = htonl( INADDR_ANY );
        memset( &(m_localinfo.sin_zero), 0, 8 );

        err = bind( m_sock, (struct sockaddr*)&m_localinfo,
            sizeof(struct sockaddr));
        if( err == -1 )
        {
            throw Exception( GetError() );
        }
        err = listen( m_sock, 8 );
        if( err == -1 )
        {
            throw Exception( GetError() );
        }

        m_listening = true;
    }

    DataSocket ListeningSocket::Accept()
    {
        sock s;
        struct sockaddr_in socketaddress;

        socklen_t size = sizeof(struct sockaddr);
        s = accept( m_sock, (struct sockaddr*)&socketaddress, &size );
        if( s == -1 )
        {
            throw Exception( GetError() );
        }
        return DataSocket( s );
    }
    void ListeningSocket::Close()
    {
        Socket::Close();

     
        m_listening = false;
    }



主要的2个文件 其他的文件明天在贴出来.对SOCKET进行封装.只为复用


#include "SocketLib/SocketLib.h"
#include <iostream>

using namespace SocketLib;

int main()
{
    ListeningSocket lsock;             
    DataSocket dsock;                  
    char buffer[128];                       
   int size = 0;                       
    int received;                      
    bool emo=false;
    unsigned long mode =!emo;
    std::cout<<mode<<std::endl;
    lsock.Listen( 5098 );              
    dsock = lsock.Accept();         

    dsock.Send( "Hello!\r\n", 8 );

    while( true )
    {
       
        received = dsock.Receive( buffer + size, 128 - size );
        size += received;

    
        if( buffer[size - 1] == '\n' )
        {
   
            std::cout << size << std::endl;

 
            dsock.Send( buffer, size );
            size = 0;
        }
    }
    return 0;
}

主执行CPP!累了一天了 终于可以休息了嘿嘿 ! 有问题可以留言呵呵!我也是刚入门C++不久

Feedback

# re: C++网络编程  回复  更多评论   

2008-11-14 13:19 by 请教问题
#include "BasicLib/BasicLib.h"

请问这个头文件是那里面的,那里可以下载?谢谢

只有注册用户登录后才能发表评论。
网站导航: 博客园   IT新闻   BlogJava   博问   Chat2DB   管理


posts - 6, comments - 6, trackbacks - 0, articles - 0

Copyright © Lemo