コード例 #1
0
int main(int argc, int argv[]) {
    std::cout << "running....\n";

    Message message("topas", "Hello World"), m2("topas", "where are you?"),
        m3("guest", "Hi");

    MessageStack messages;
    messages.append(&message);
    messages.append(&m2);
    messages.append(&m3);

    pthread_t tid;
    pthread_attr_t attr;

    pthread_attr_init(&attr);
    pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);

    try {
        pthread_create(&tid, &attr, &game, NULL);
        while (true) {

            try{
                ServerSocket *new_sock = new ServerSocket;
                server.accept(*new_sock);

                pthread_create(&tid, &attr, &rundle, new_sock);
            }
            catch (SocketException& e) {
                std::cout << "Exception was caught:" << e.description()
                        << "\nExiting.\n";
            }
        }
    } catch (SocketException& e) {
        std::cout << "Exception was caught:" << e.description()
                << "\nExiting.\n";
    }

    return 0;
}
コード例 #2
0
void* rundle(void* socket){
    ServerSocket *client = (ServerSocket *) socket;
    std::string data;

    MessageStack messages;

    UserStack users;
    User *user;

    try {
        user = init_connection(client);
    }
    catch (SocketException& e) {
        printf("Error initial connection in function rundle()\n");
        return NULL;
    }

    try {
        users.join(user);
        user->send("Добро пожаловать, о ");
        user->send("\n---- // enter \"quit\" for exit\n\n");
        user->send(messages.viewLast());


        while (true) {
            data = *user->recive("> ");
            data = trimr(data);
            if ( data.compare("quit") == 0) {
                user->send("Bye! До скорых встреч");
                sleep(2);
                break;
            }
            if ( data.compare("help") == 0){
                user->send("\r==== Список пользователей ====\n");
            }
            if ( data.compare("who") == 0){
                user->send("\r==== Список пользователей ====\n");
                std::vector <User*> list = users.list();
                for (int i = list.size() - 1; i >= 0; --i){
                    user->send(list[i]->id);
                    user->send(": ");
                    user->send(list[i]->getName());
                    user->send("\n");
                }
                continue;
            }


            if ( data.length() == 0){
                continue;
            }

            Message *message = new Message(user->getName(), data);
            messages.append( message );
            users.sendMessage(message->get().c_str());
        }
    } catch (SocketException& e) {
        std::cout << "Exception was caught:" << e.description()
                << "\nExiting.\n";
    }

    users.disconnect(user);

    delete client;

    return NULL;
}