用于多客户C服务器的异步C客户端

时间:2015-04-19 11:59:45

标签: c sockets client server

我有一个工作正常的客户端,但每当我运行一个新的客户端时,有时我不会在已经运行的另一个客户端上收到已发送的消息,而使用telnet它可以完美地工作,消息“广播”给所有人连接客户端,我希望每当收到一条消息给客户端显示即使我还没有发送消息。 我应该在客户端上使用select吗?什么应该改变?

client.c:

#include <stdio.h> //printf
#include <string.h>    //strlen
#include <sys/socket.h>    //socket
#include <arpa/inet.h> //inet_addr
#include <unistd.h> 

int main(int argc , char *argv[]){
    int sock;
    struct sockaddr_in server;
    char message[256] , server_reply[256];

    //Create socket
    sock = socket(AF_INET , SOCK_STREAM , 0);
    if (sock == -1)
    {
        printf("Could not create socket");
    }
    puts("Socket created");

    server.sin_addr.s_addr = inet_addr("127.0.0.1");
    server.sin_family = AF_INET;
    server.sin_port = htons( 9034 );

    //Connect to remote server
    if (connect(sock , (struct sockaddr *)&server , sizeof(server)) < 0){
        perror("connect failed. Error");
        return 1;
    }

    puts("Connected\n");    

    //keep communicating with server
    for(;;){

    printf("Enter message: ");
    memset(message, 0, 256);
    fgets(message, 256,stdin);
    // scanf("%s" , message);

        //Send some data
        if( send(sock , message , strlen(message) , 0) < 0)
        {
            puts("Send failed");
            return 1;
        }

        //Receive a reply from the server
        if( recv(sock , server_reply , 256 , 0) < 0)
        {
            puts("recv failed");
            break;
        }

    printf("Server Reply: %s\n", server_reply);
    server_reply[0]='\0'; 
    }

    close(sock);
    return 0;
}

server.c:

/*
** selectserver.c -- a cheezy multiperson chat server
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <netdb.h>

#define PORT "9034"   // port we're listening on

// get sockaddr, IPv4 or IPv6:
void *get_in_addr(struct sockaddr *sa)
{
    if (sa->sa_family == AF_INET) {
        return &(((struct sockaddr_in*)sa)->sin_addr);
    }

    return &(((struct sockaddr_in6*)sa)->sin6_addr);
}

int main(void){
    fd_set master;    // master file descriptor list
    fd_set read_fds;  // temp file descriptor list for select()
    int fdmax;        // maximum file descriptor number

    int listener;     // listening socket descriptor
    int newfd;        // newly accept()ed socket descriptor
    struct sockaddr_storage remoteaddr; // client address
    socklen_t addrlen;

    char buf[256];    // buffer for client data
    int nbytes;

    char remoteIP[INET6_ADDRSTRLEN];

    int yes=1;        // for setsockopt() SO_REUSEADDR, below
    int i, j, rv;

    struct addrinfo hints, *ai, *p;

    FD_ZERO(&master);    // clear the master and temp sets
    FD_ZERO(&read_fds);

    // get us a socket and bind it
    memset(&hints, 0, sizeof hints);
    hints.ai_family = AF_UNSPEC;
    hints.ai_socktype = SOCK_STREAM;
    hints.ai_flags = AI_PASSIVE;
    if ((rv = getaddrinfo(NULL, PORT, &hints, &ai)) != 0) {
        fprintf(stderr, "selectserver: %s\n", gai_strerror(rv));
        exit(1);
    }

    for(p = ai; p != NULL; p = p->ai_next) {
        listener = socket(p->ai_family, p->ai_socktype, p->ai_protocol);
        if (listener < 0) { 
            continue;
        }

        // lose the pesky "address already in use" error message
        setsockopt(listener, SOL_SOCKET, SO_REUSEADDR, &yes, sizeof(int));

        if (bind(listener, p->ai_addr, p->ai_addrlen) < 0) {
            close(listener);
            continue;
        }

        break;
    }

    // if we got here, it means we didn't get bound
    if (p == NULL) {
        fprintf(stderr, "selectserver: failed to bind\n");
        exit(2);
    }

    freeaddrinfo(ai); // all done with this

    // listen
    if (listen(listener, 10) == -1) {
        perror("listen");
        exit(3);
    }

    // add the listener to the master set
    FD_SET(listener, &master);

    // keep track of the biggest file descriptor
    fdmax = listener; // so far, it's this one

    // main loop
    for(;;) {
        read_fds = master; // copy it
        if (select(fdmax+1, &read_fds, NULL, NULL, NULL) == -1) {
            perror("select");
            exit(4);
        }

        // run through the existing connections looking for data to read
        for(i = 0; i <= fdmax; i++) {
            if (FD_ISSET(i, &read_fds)) { // we got one!!
                if (i == listener) {
                    // handle new connections
                    addrlen = sizeof remoteaddr;
                    newfd = accept(listener,
                        (struct sockaddr *)&remoteaddr,
                        &addrlen);

                    if (newfd == -1) {
                        perror("accept");
                    } else {
                        FD_SET(newfd, &master); // add to master set
                        if (newfd > fdmax) {    // keep track of the max
                            fdmax = newfd;
                        }
                        printf("selectserver: new connection from %s on "
                            "socket %d\n",
                            inet_ntop(remoteaddr.ss_family,
                                get_in_addr((struct sockaddr*)&remoteaddr),
                                remoteIP, INET6_ADDRSTRLEN),
                            newfd);
                    }
                } else {
                    // handle data from a client
                    memset(buf, 0, 256);
                    if ((nbytes = recv(i, buf, sizeof buf, 0)) <= 0) {
                        // got error or connection closed by client
                        if (nbytes == 0) {
                            // connection closed
                            printf("selectserver: socket %d hung up\n", i);
                        } else {
                            perror("recv");
                        }
                        close(i); // bye!
                        FD_CLR(i, &master); // remove from master set
                    } else {
                        // we got some data from a client
                        for(j = 0; j <= fdmax; j++) {
                            // send to everyone!
                            if (FD_ISSET(j, &master)) {
                                // except the listener and ourselves
                                if (j != listener && j != i) {
                                    if (send(j, buf, nbytes, 0) == -1) {
                                        perror("send");
                                    }
                                }
                            }
                        }
                    }
                } // END handle data from client
            } // END got new incoming connection
        } // END looping through file descriptors
    } // END for(;;)--and you thought it would never end!

    return 0;
}

1 个答案:

答案 0 :(得分:5)

客户端发送消息之前无法接收消息的原因是因为。

fgets(message, 256,stdin);

Will keep "reading" (and will therefore block) until an EOF or a newline character has been read from the input stream

另外,请注意

if( recv(sock , server_reply , 256 , 0) < 0)

blocks if there is nothing to read,这将阻止该用户向服务器发送更多消息,直到从服务器读取新内容。假设你以前玩过网络游戏,我希望你能看到这样的设置会让人讨厌!

因此,我们必须找到一些检查,看看我们是否可以从 STDIN 服务器套接字中读取而不会产生阻止。使用 select()会阻止我们阻止服务器套接字,但在使用 fgets()时对 STDIN 不起作用来读取用户的输入。这是因为,如上所述, fgets()会阻止,直到检测到 EOF 或换行符。

我想到的主要解决方案是使用方法 buffer_message()替换 fgets ,该方法仅在赢取时从 STDIN 读取阻止读取(我们将使用 select()来实现此功能)。然后我们将读取的内容放入缓冲区。如果有完整消息,则此消息将写入服务器。否则,我们会让控件继续执行程序,直到有东西要读或写。

这是我最近一次大学任务的代码,所以代码的一小部分不是我的

声明:

//directives are above (e.g. #include ...)

//message buffer related delcartions/macros
int buffer_message(char * message);
int find_network_newline(char * message, int inbuf);
#define COMPLETE 0
#define BUF_SIZE 256

static int inbuf; // how many bytes are currently in the buffer?
static int room; // how much room left in buffer?
static char *after; // pointer to position after the received characters
//main starts below

主:

//insert the code below into main, after you've connected to the server
puts("Connected\n");    

//set up variables for select()
fd_set all_set, r_set;
int maxfd = sock + 1;
FD_ZERO(&all_set);
FD_SET(STDIN_FILENO, &all_set); FD_SET(sock, &all_set);
r_set = all_set;
struct timeval tv; tv.tv_sec = 2; tv.tv_usec = 0;

//set the initial position of after
after = message;

puts("Enter message: ");
//keep communicating with server
for(;;){

    r_set = all_set;
    //check to see if we can read from STDIN or sock
    select(maxfd, &r_set, NULL, NULL, &tv);

    if(FD_ISSET(STDIN_FILENO, &r_set)){

        if(buffer_message(message) == COMPLETE){
            //Send some data
            if(send(sock, message, strlen(message) + 1, 0) < 0)//NOTE: we have to do strlen(message) + 1 because we MUST include '\0'
            {
                puts("Send failed");
                return 1;
            }

            puts("Enter message:");
        }
    }

    if(FD_ISSET(sock, &r_set)){
        //Receive a reply from the server
        if( recv(sock , server_reply , 256 , 0) < 0)
        {
            puts("recv failed");
            break;
        }

        printf("\nServer Reply: %s\n", server_reply);
        server_reply[0]='\0';

    }
}

close(sock);
return 0;
//end of main

缓冲功能:

int buffer_message(char * message){

    int bytes_read = read(STDIN_FILENO, after, 256 - inbuf);
    short flag = -1; // indicates if returned_data has been set 
    inbuf += bytes_read;
    int where; // location of network newline

    // Step 1: call findeol, store result in where
    where = find_network_newline(message, inbuf);
    if (where >= 0) { // OK. we have a full line

        // Step 2: place a null terminator at the end of the string
        char * null_c = {'\0'};
        memcpy(message + where, &null_c, 1); 

        // Step 3: update inbuf and remove the full line from the clients's buffer
        memmove(message, message + where + 1, inbuf - (where + 1)); 
        inbuf -= (where+1);
        flag = 0;
    }

    // Step 4: update room and after, in preparation for the next read
    room = sizeof(message) - inbuf;
    after = message + inbuf;

    return flag;
}

int find_network_newline(char * message, int bytes_inbuf){
    int i;
    for(i = 0; i<inbuf; i++){
        if( *(message + i) == '\n')
        return i;
    }
    return -1;
}

<强> P.S。

if( send(sock , message , strlen(message) , 0) < 0)

如果没有空间写入服务器,上面也可以阻止,但这里不需要担心。另外,我想指出一些你应该为客户端和服务器实现的东西:

  1. Whenever you send data over a network, the standard newline is \r\n, or carriage return / newline, or simply the network newline.客户端和服务器之间发送的所有消息都应在末尾添加此消息。
  2. 您应该缓冲服务器和客户端之间发送的所有数据。为什么?因为您不能保证在单次读取套接字时接收消息中的所有数据包。我没有时间找到源,但是当使用TCP / IP时,消息/文件的数据包不必一起到达,这意味着如果您执行了读取,则可能无法读取您想要的所有数据阅读。 我对此并不熟悉,所以请进一步调查。打开此编辑/更正