Socket封装6

来源:互联网 发布:mdf数据格式文件 编辑:程序博客网 时间:2024/06/01 08:52

#ifndef SOCK_SERVERSOCKET_H
#define SOCK_SERVERSOCKET_H


// #include <standard library headers>

// #include <other library headers>

// #include "customer headers"
#include "Socket.h"


namespace sock
{

    class ServerSocket : public Socket
    {
    public:
        ServerSocket(int port)
        {
            if (!Socket::Create())
            {
                throw SocketException("Could not create server socket.");
            }
            if (!Socket::Bind(port))
            {
                throw SocketException("Could not bind to port.");
            }
            if (!Socket::Listen())
            {
                throw SocketException("Could not listen to socket.");
            }
        }
        ServerSocket() {}
        virtual ~ServerSocket() {}


    public:
        const ServerSocket& operator << (const std::string& s) const
        {
            if (!Socket::Send(s))
            {
                throw SocketException ( "Could not write to socket." );
            }
            return *this;
        }
        const ServerSocket& operator >> (std::string& s) const
        {
            if (Socket::Recv(s) < 0)
            {
                throw SocketException("Could not read from socket.");
            }
            return *this;
        }

        void Accept(ServerSocket& sock, int sec = -1, int usec = -1)
        {
            if (!Socket::Accept(sock, sec, usec))
            {
                throw SocketException("Could not accept socket.");
            }
        }

    };

}

#endif // SOCK_SERVERSOCKET_H

原创粉丝点击