服务器程序停留在read()函数上,但write()函数在客户端程序中运作良好

时间:2019-05-19 13:49:48

标签: c linux sockets network-programming

我正在使用C中的 socket编程方法来开发简单的聊天室程序。我已经实现了客户端可以连接到服务器并将消息发送到服务器,并且服务器应该将消息分发给其他人。

但是当我尝试测试我的程序并试图使两个客户端通信时,会发生一些奇怪的事情。如果执行以下步骤,将会发生奇怪的事情。

  1. 运行服务器程序并等待连接。
  2. 打开一个客户端程序并连接到服务器,然后发送两条消息,两者均成功运行。
  3. 打开另一个客户端并执行相同的操作,第一个客户端可以接收第二个客户端发送的完美消息。
  4. 但是当我切换到第一台服务器并尝试编写新消息并发送到要分发的服务器时,它失败了。并且第二个客户端和服务器都无法接收到此消息。
  5. 经过一些调试后,服务器程序似乎卡在了read()函数上。 顺便说一下,我在不同终端上的 Uubuntu18.04虚拟机上完成了所有这些操作

更多点:

  1. 我尝试调试并打印所有可以获得的值,似乎客户端程序的write()函数正常运行,但是服务器程序停止在Receive内部的第二个函数read()处线程。
  2. 我认为这可能是有关read()函数的阻塞状态的问题,但是我是网络编程的新手,对此我并不了解。

这是我的问题的屏幕截图(聊天室:左是服务器,右是两个客户端):

Chat-room:Left is a server, right are two clients

这是我的client.c和server.c代码,我已经指出了发生此问题的位置。

客户端C

/* tcp-client.c */
#include <stdio.h>
#include <fcntl.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <strings.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <string.h>
#include <pthread.h>
#include <stdlib.h>

//send the message to the server any time terminal get input
void*  Send(void* Socked)
{
    char sender[80];
    //save the socked into a int pointer
    int *SockedCopy = Socked;
    while(fgets(sender, sizeof(sender), stdin)){
        //whenever enter a string, send it
        int messageSize = strlen(sender) + 1;
        write(*SockedCopy, &messageSize, sizeof(int));
        int i = write(*SockedCopy, sender, messageSize);      //both work when sending message
        printf("write over! the write() returns %d\n", i);
        //check whether this is a quit message
        if(strcmp(sender, "q!") == 0)
            exit(1);

    }
}


//receive message from server
void* Receive(void* Socked)
{
    int *SockedCopy = Socked;
    char Receiver[80];

    while(1){
        //read message continuosly
        int reveiverEnd = 0;
        reveiverEnd  = read (*SockedCopy, Receiver, 1000);
        Receiver[reveiverEnd] = '\0';   
        fputs(Receiver, stdout);
        Receiver[0] = '\0';
    }
}

int main ()
{
    int sockfd, n;
    pthread_t threadSend;
    pthread_t threadReceive;
    struct sockaddr_in serv, cli;
    char rec[1000];
    char send[80];

    //input UserName
    printf("Input Username:" );
    fgets(send, sizeof(send), stdin);
    send[strlen(send) - 1] = '\0';
    int MessageSize = strlen(send);

    //create socked
    sockfd = socket (PF_INET, SOCK_STREAM, 0);

    //create server information
    bzero (&serv, sizeof (serv));
    serv.sin_family = PF_INET;
    serv.sin_port = htons (8888);
    serv.sin_addr.s_addr = inet_addr ("127.0.0.1" /*local machine*/);

    //connect to the server
    connect (sockfd, (struct sockaddr *) &serv, sizeof (struct sockaddr));

    //send the user name to the server
    write(sockfd, &MessageSize, sizeof(int));
    write (sockfd, send, sizeof(send));

    //get successfully connecting message
    n = read (sockfd, rec, 1000);//n marks real length
    rec[n] = '\0';  
    fputs(rec, stdout);

    send[0] = '\0';

    //open send thread  
    pthread_create(&threadSend, 0, Send, &sockfd);

    //open receiving message thread
    pthread_create(&threadReceive, 0, Receive, &sockfd);

    //close socked and close two threads
    for(int i = 0; i < 100; ++i)
        sleep(100000);
    pthread_exit(&threadSend);
    pthread_exit(&threadReceive);
    close(sockfd);

    return 0;
}

SERVER.C

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <pthread.h>
#include <sys/socket.h>
#include <linux/in.h>
#include <unistd.h>
#include <unistd.h>

pthread_t thread;
pthread_t threadClient[100];
int ServerSock;

//Every client's information
typedef struct
{
    int sock;
    char UserName[16]; 
    struct sockaddr address;
    int addr_len;
} connection_t;
static connection_t conn[100];

//this function distributes the messsage/status of single client to the other
//Info is the message needed to be distributed
int SendInfo(void* Info)
{
    char *info = Info;
    for(int i = 0; i < 100; ++i)
        //send to the client that exists and doesn't quit room
        if(conn[i].addr_len != -1 && conn[i].addr_len != 0){
            if(send (conn[i].sock, info , strlen(info) + 1, 0) == -1)
                printf("error occured, send to %s fail", conn[i].UserName);
            printf("send %s to %s successfully!\n", info, conn[i].UserName);
        }   
    return 0;   
}


//This function deals with single client, aim to receive message from this client
//and then send them to another using SendIinfo
void* Receive(void* clientnumber)
{
    int* Clientnumber = clientnumber;
    while(1)
    {
        //read the message from the client
        char *Buffer;
        int messageLen = 0;
        read(conn[*Clientnumber].sock, &messageLen, sizeof(int));
        printf("receive from %d\n", messageLen);
        if(messageLen > 0)
        {
            Buffer = (char *)malloc((messageLen+1)*sizeof(char));
            read(conn[*Clientnumber].sock, Buffer, messageLen);   // the program stucks here and don't know why

            if(Buffer[0] != ':') continue;
            Buffer[messageLen] = '\0';
            //whether the client want to quit
            if( Buffer[1] == 'q' && Buffer[2] == '!' )
            {
                //constitute quit message and delete this client
                char quit[] = " quit the chat room";
                char quitMessage[20];       
                quitMessage[0] = '\0';
                strcat(conn[*Clientnumber].UserName, quit); 
                SendInfo(quitMessage);
                conn[*Clientnumber].addr_len = -1;
                pthread_exit(&threadClient[*Clientnumber]);
            }
            else{
                //constitute the message
                char begin[] = " says";
                char messageDistribute[200];
                messageDistribute[0] = '\0';
                strcat(messageDistribute, conn[*Clientnumber].UserName);
                strcat(messageDistribute, begin);
                strcat(messageDistribute, Buffer);
                SendInfo(messageDistribute);
            }
            free(Buffer);
        }
        else
            continue;
    }
}



//aim to accept whenever there is a client trying to connect
void * process(void * ptr)
{
    pthread_t clientThread[100];
    char * buffer;
    int len;
    //the number of the client connecting now
    int clientNumber = 0;      
    long addr = 0;
    while(1){
        //waiting to be connected
        if(clientNumber < 100)
        {
            conn[clientNumber].sock = accept(ServerSock, &conn[clientNumber].address, &conn[clientNumber].addr_len);
        }
        else
            break;


        //the length of the message
        read(conn[clientNumber].sock, &len, sizeof(int));
        if (len > 0)
        {

            //multiple information of a client
            addr = (long)((struct sockaddr_in *)&conn[clientNumber].address)->sin_addr.s_addr;
            buffer = (char *)malloc((len+1)*sizeof(char));
            buffer[len] = 0;
            read(conn[clientNumber].sock, buffer, len);


            //send success message to the client
            send (conn[clientNumber].sock, "You have entered the chatroom, Start CHATTING Now!\n", 51, 0);


            //save client's nick name
            strcpy(conn[clientNumber].UserName, buffer);


            printf("User <%s> has entered the Chatroom!\n", conn[clientNumber].UserName);
            printf("There are %d people in Chatroom now!\n",clientNumber+1);
            free(buffer);

            //create a thread dealing the messages from a single client
            int number = clientNumber;
            pthread_create(&threadClient[clientNumber], 0, Receive, &number);
        }
        clientNumber += 1;

    }
    pthread_exit(0);
}

int main(int argc, char ** argv){
    struct sockaddr_in address;
    int port = 8888;
    connection_t * connection;

    //create socked
    ServerSock = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);

    //bind the socked to a port
    address.sin_family = AF_INET;
    address.sin_addr.s_addr = INADDR_ANY;
    address.sin_port = htons(port);
    if (bind(ServerSock, (struct sockaddr *)&address, sizeof(struct sockaddr_in)) < 0)
    {
        fprintf(stderr, "error: cannot bind socket to port %d\n", port);
        return -4;
    }


    //listen for connections
    listen(ServerSock, 100);
    printf("the server is ready and listening\n");


    //creating a thread dealing with connections
    pthread_create(&thread, 0, process, (void *)connection);


    //keep this program working
    for(int i = 0; i < 100; ++i)
        sleep(10000);


    //close socked and thread
    pthread_detach(thread);
    close(ServerSock);
    return 0;
}

这是用于学术作业。

1 个答案:

答案 0 :(得分:0)

您的问题根本不是网络问题,而是您如何将clientnumber参数传递到Receive线程的错误:

 if (len > 0)
 {
    [...]

    int number = clientNumber;
    pthread_create(&threadClient[clientNumber], 0, Receive, &number);
 }  // number gets destroyed here

请注意,在上面的代码中,number是局部变量,这意味着它将在范围退出时(即,一旦执行到达上面的}行)被销毁。

但是,您正在将指向number(即&number)的指针传递到Receive线程,并且您的Receive线程尝试使用该指针来查找有关客户端的数据。这意味着Receive线程正在取消引用一个悬空指针,该指针将引发未定义的行为。 (在这种情况下,我看到的是程序会在短时间内工作,然后停止工作,因为内存位置Clientnumber指向的位置已被其他一些数据覆盖,因此下次Receive线程尝试解除对指针的引用,最终导致查看错误的数据,因此在错误的套接字fd上调用read() ...但是从原理上讲,任何事情都可能发生,因为一旦调用未定义的行为,所有投注均关闭)

在任何情况下,解决此问题的一种简单方法是直接将指针传递到connection_t对象,而不是传递索引,即:

pthread_create(&threadClient[clientNumber], 0, Receive, &conn[clientNumber] );

....然后可以直接在Receive线程中使用该指针:

void* Receive(void* arg)
{
   connection_t * conn = (connection_t *) arg; 

   [...]

   int r = read(conn->sock, &messageLen, sizeof(int));

以这种方式执行操作不会调用未定义的行为,因为connection_t conn[100];数组被声明为静态/全局数组,因此保证其中的对象在进程退出之前不会被破坏。

如果仍然需要从clientNumber内部访问Receive()索引值,则可以将该值添加为connection_t结构定义中的另一个字段。