Exemplo n.º 1
0
/*
 * 起一个监听端口。
 *
 * @param spec: 格式 [upd|tcp]:ip:port
 * @param streamer: 数据包的双向流,用packet创建,解包,组包。
 * @param serverAdapter: 用在服务器端,当Connection初始化及Channel创建时回调时用
 * @return IO组件一个对象的指针
 */
IOComponent *Transport::listen (const char *spec, IPacketStreamer *streamer, 
                                IServerAdapter *serverAdapter, int timeout) {
    MutexGuard guard(&_stopMutex);
    if (_stop) { 
        ANET_LOG(SPAM, "Transport(%p) Stoped!", this);
        return NULL; 
    }
    if (NULL == spec || NULL == streamer || NULL == serverAdapter) {
        ANET_LOG(WARN, "Invalid parameters for listen(%p,%p,%p)",
                 spec, streamer, serverAdapter);
        return NULL;
    }

    char tmp[512];
    char *args[32];
    strncpy(tmp, spec, 512);
    tmp[511] = '\0';

    if (parseAddr(tmp, args, 32) != 3) {
        return NULL;
    }

    if (strcasecmp(args[0], "tcp") == 0) {
        char *host = args[1];
        int port = atoi(args[2]);

        // Server Socket
        ServerSocket *socket = new ServerSocket();
        assert(socket);
        if (!socket->setAddress(host, port)) {
            delete socket;
            return NULL;
        }

        // TCPAcceptor
        TCPAcceptor *acceptor 
            = new TCPAcceptor(this, socket, streamer, serverAdapter, timeout);
        assert(acceptor);
        if (!acceptor->init()) {
            delete acceptor;
            return NULL;
        }
        // 返回
        return acceptor;
    } else if (strcasecmp(args[0], "udp") == 0) {}

    return NULL;
}
/*
 * 起一个监听端口。
 *
 * @param spec: 格式 [upd|tcp]:ip:port
 * @param streamer: 数据包的双向流,用packet创建,解包,组包。
 * @param serverAdapter: 用在服务器端,当Connection初始化及Channel创建时回调时用
 * @return IO组件一个对象的指针
 */
IOComponent *Transport::listen(const char *spec, IPacketStreamer *streamer, 
								IServerAdapter *serverAdapter) {
    char tmp[1024];
    char *args[32];
    strncpy(tmp, spec, 1024);
    tmp[1023] = '\0';

    if (parseAddr(tmp, args, 32) != 3) {
        return NULL;
    }

    if (strcasecmp(args[0], "tcp") == 0) {
        char *host = args[1];
        int port = atoi(args[2]);

        // Server Socket
        ServerSocket *socket = new ServerSocket();

        if (!socket->setAddress(host, port)) {
            delete socket;
            return NULL;
        }

        // TCPAcceptor
        TCPAcceptor *acceptor = new TCPAcceptor(this, socket, streamer, serverAdapter);

        if (!acceptor->init()) {
            delete acceptor;
            return NULL;
        }

        // 加入到iocomponents中,及注册可读到socketevent中
        addComponent(acceptor, true, false);

        // 返回
        return acceptor;
    } else if (strcasecmp(args[0], "udp") == 0) {}

    return NULL;
}