UNIX中的域域套接字编程,打印问题

时间:2015-05-10 01:28:28

标签: c sockets unix-socket

我的服务器出现打印问题。当我在终端上有2个或更多客户端活动时,我希望同时打印。但是,我一次只能从一个客户端打印。关闭客户端后,其他客户端可以自由写入服务器。我该怎么做才能解决我的问题?

我试图分割打印部分,我认为它并没有真正做任何事情。 (刚才意识到如果我这样做,那么选择系统调用是一种浪费,我宁愿使用select系统调用)*编辑

while(TRUE) {

    FD_ZERO(&readfds);

    FD_SET(socket1, &readfds);
    FD_SET(socket2, &readfds);
    FD_SET(socket3, &readfds);

    select(socket3+1, &readfds, NULL, NULL, NULL);

    //add socket1
    if(FD_ISSET(socket1, &readfds)) {
        if((client_socket1 = accept(socket1, NULL, NULL)) < 0) {
            perror("accept1");
            exit(EXIT_FAILURE);
        }
        printf("New Connection\n");

        puts("Welcome message1 sent successfully\n");
    }

    //add socket2
    if(FD_ISSET(socket2, &readfds)) {
        if((client_socket2 = accept(socket2, (struct sockaddr *)&addr2, (socklen_t*)&addr2)) < 0) {
            perror("accept2");
            exit(EXIT_FAILURE);
        }
        printf("New Connection\n");

        puts("Welcome message2 sent successfully\n");
    }

    //add socket 3
    if(FD_ISSET(socket3, &readfds)) {
        if((client_socket3 = accept(socket3, (struct sockaddr *)&addr3, (socklen_t*)&addr3)) < 0) {
            perror("accept3");
            exit(EXIT_FAILURE);
        }
        printf("New Connection\n");

        puts("Welcome message3 sent successfully\n");
    }

    //print from socket 3
    while( (ready = read(client_socket3, buffer, sizeof(buffer))) > 0) {
        printf("%s\n", buffer);
    }

    //print from socket 2
    while( (ready = read(client_socket2, buffer, sizeof(buffer))) > 0) {
        printf("%s\n", buffer);
    }

    //print from socket 1
    while( (ready = read(client_socket1, buffer, sizeof(buffer))) > 0) {
        printf("%s\n", buffer);
    }
}

1 个答案:

答案 0 :(得分:0)

在尝试从中读取客户端套接字之前,需要将其添加到fd_setselect语句中。此外,您应该使所有套接字无阻塞。否则,read调用将阻止,直到您获得数据。

这是一个使用recv代替read来读取套接字但使用MSG_DONTWAIT的异步标志的快速修复。

我没有看到您关闭客户端套接字或正确处理错误的任何地方。所以我插入了一些代码作为提示。此外,直接从套接字“打印”数据缓冲区永远不是一个好主意。因为您永远不知道您收到的数据是否为空终止。从套接字读取数据后,始终为null终止缓冲区。

更改此代码块:

//print from socket 3
while( (ready = read(client_socket3, buffer, sizeof(buffer))) > 0) {
    printf("%s\n", buffer);
}

对此:

while (1)
{
    int result;
    result = recv(client_socket3, buffer, sizeof(buffer)-1, MSG_DONTWAIT);
    if ((result == -1) && 
             ((errno == EAGAIN) || (errno==EWOULDBLOCK)) )
    {
        // no more data available, but could be available later
        // use the socket with "select" above to wait for more data
    }
    else if ((result == -1) || (result == 0))
    {
        // remote close or unrecoverable error
        close(client_socket3);
        client_socket3=-1;
    }
    else
    {
        // null terminate the buffer before printing
        buffer[result] = '\0';
        printf("%s\n", buffer);
    }
}