【问题标题】:Sockets and threads in CC中的套接字和线程
【发布时间】:2019-04-09 18:13:10
【问题描述】:

我在尝试在服务器端实现具有多线程的客户端-服务器程序时遇到了一个小问题。我的想法是让服务器永远旋转,尽可能接受客户端,然后使用线程将其发送到 client_handle() 函数。

问题出在这里:我的服务器和客户端正在使用下面的代码。在服务器的初始响应点,它发送ALL_GOOD_CD 失败。我不确定为什么会这样,因为我之前在一行中打印出客户端的套接字 fd,它似乎与接受时提供给我们的文件描述符匹配。

一个想法是我的套接字 id 没有正确地传递给线程。我的客户端似乎从未收到 ALL_GOOD_CD(它在与服务器连接后阻塞了 recv() 调用)。我是线程和套接字的新手,任何事情都会有所帮助;谢谢!

这是运行所需的客户端代码:

#include <stdio.h>      /* for printf() and fprintf() */
#include <sys/socket.h> /* for socket(), connect(), send(), and recv() */
#include <arpa/inet.h>  /* for sockaddr_in and inet_addr() */
#include <stdlib.h>     /* for atoi() and exit() */
#include <string.h>     /* for memset() */
#include <unistd.h>     /* for close() */

void DieWithError(char *errorMessage);  /* Error handling function */
int main(int argc, char *argv[])
{
    int sock;                           /* Socket descriptor */
    struct sockaddr_in server_addr;     /* Server address */
    unsigned short server_port;         /* Server port */
    char *server_ip;                    /* Server IP address (dotted quad) */
    char server_response[300];   /* Buffer to hold response from the server */
    char* username;

    /* Test for correct number of arguments */
    if (argc != 4) {
        fprintf(stderr, "Usage: %s <server_ip> <server_port> <username>\n", argv[0]);
        exit(1);
    }

    server_ip = argv[1];            /* Second arg: server IP address (dotted quad) */
    server_port = atoi(argv[2]);    /* Third arg: server port number */
    username = argv[3];             /* Fourth arg: username */

    /* Create a reliable, stream socket using TCP */
    if ((sock = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP)) < 0)
        DieWithError("socket() failed");

    /* Construct the server address structure */
    memset(&server_addr, 0, sizeof(server_addr));       /* Zero out structure */
    server_addr.sin_family      = AF_INET;              /* Internet address family */
    server_addr.sin_addr.s_addr = inet_addr(server_ip); /* Server IP address */
    server_addr.sin_port        = htons(server_port);   /* Server port */

    /* Establish the connection to the server */
    if (connect(sock, (struct sockaddr*) &server_addr, sizeof(server_addr)) < 0)
        DieWithError("connect() failed, could not find server.");

    printf("connected\n");

    memset(&server_response, 0, 300);
    if (recv(sock, server_response, 300, 0) < 0)
        DieWithError("recv() for initial response failed");

    printf("received initial reponse\n");
}

void DieWithError(char* errorMessage) {
    fprintf(stderr, "Dying with error sadface: %s\n", errorMessage);
    exit(1);
}

这是尽可能缩小的服务器代码:

#include <stdio.h>      /* for printf() and fprintf() */
#include <sys/socket.h> /* for socket(), connect(), send(), and recv() */
#include <arpa/inet.h>  /* for sockaddr_in and inet_addr() */
#include <stdlib.h>     /* for atoi() and exit() */
#include <string.h>     /* for memset() */
#include <unistd.h>     /* for close() */
#include <pthread.h>    /* multithreading the clients! */

#define MAXMSGSIZE 150
#define MAXCLIENTS 5
#define TOO_MANY_CD 0
#define ALL_GOOD_CD 1
#define OTHER_BAD_CD 2

struct client {
    char* username;
    char** subs;
    int socket;
    char temp_msg[MAXMSGSIZE*2];
};

void DieWithError(char* errorMessage);  /* Error handling function */
void handle_client(void* new_socket); /* Client handling function */

static struct client** clients;
static pthread_t* threads;
static pthread_mutex_t clients_mutex;
static pthread_mutex_t threads_mutex;

int main(int argc, char *argv[])
{
    int server_sock;                /* Server socket descriptor */
    unsigned short server_port;     /* Echo server port */
    struct sockaddr_in server_addr; /* sockaddr_in struct to hold information about the server */
    int server_addr_size;           /* Size of server_addr struct in bytes */
    int client_sock;
    int empty_thread;
    pthread_attr_t thread_attr;

    if (argc != 2) {  /* Test for correct number of arguments */
        fprintf(stderr, "Usage: %s <server_port>\n", argv[0]);
        exit(1);
    }

    clients = (struct client**) calloc(1, sizeof(struct client*) * MAXCLIENTS);
    if (clients == NULL)
        DieWithError("calloc() for clients failed");
    threads = (pthread_t*) calloc(1, sizeof(pthread_t) * MAXCLIENTS);
    if (clients == NULL)
        DieWithError("calloc() for clients failed");

    pthread_mutex_init(&clients_mutex, NULL);
    pthread_mutex_init(&threads_mutex, NULL);
    pthread_attr_init(&thread_attr);
    pthread_attr_setdetachstate(&thread_attr, PTHREAD_CREATE_DETACHED);

    server_port = atoi(argv[1]);

    /* Create a reliable, stream socket using TCP */
    if ((server_sock = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP)) < 0)
        DieWithError("socket() failed");

    // Zero out server_addr var and fill with information
    memset(&server_addr, 0, sizeof(server_addr));
    server_addr.sin_family = AF_INET;
    server_addr.sin_addr.s_addr = htonl(INADDR_ANY);
    server_addr.sin_port = htons(server_port);

    // Bind server with sock, IP, and port so that the clients can connect to us
    if (bind(server_sock, (struct sockaddr*) &server_addr, sizeof(server_addr)) < 0)
        DieWithError("bind() failed");

    // Allow this server to accept 5 clients at a time (queue has 0 capacity because we multithread)
    if (listen(server_sock, 0) < 0)
        DieWithError("listen() failed");

    // Display some information so we can connect with client
    printf("Using\n\tport: %d\n\tIP: %s\n", server_port, inet_ntoa(server_addr.sin_addr));
    server_addr_size = sizeof(server_addr);
  for (;;) {
    int* new_socket = (int*)malloc(sizeof(int));
    if ((*new_socket = accept(server_sock, 
        (struct sockaddr*) &server_addr, &server_addr_size)) < 0) {
      printf("accept() failed");
      continue;
    }
    int free_spot = -1;
    for (int i = 0; i < MAXCLIENTS; i++)
        if (!threads[i]) free_spot = i;
    if (free_spot == -1) {
        printf("no empty threads (max clients handled currently)");
        send(*new_socket,(void*) OTHER_BAD_CD, sizeof(OTHER_BAD_CD), 0);
        close(*new_socket);
        continue;
    }

    if (pthread_create(&threads[free_spot], &thread_attr,
        (void*) &handle_client, (void*) new_socket)) {
      printf("pthread_create failed");
      close(*new_socket);
      continue;
    }
    printf("sent new client %d to handle_client()\n", *new_socket);
  }
}

void handle_client(void* new_socket) {
    int socket = *(int*)new_socket;
    free(new_socket);
    printf("handling new client %d\n", socket);
    struct client* curr_cl;
    pthread_mutex_lock(&clients_mutex);
    printf("locked mutex?\n");
    if (send(socket, (void*)ALL_GOOD_CD, sizeof(ALL_GOOD_CD), 0) < 0) {
        printf("inital all good resp failed");
        send(socket, (void*)OTHER_BAD_CD, sizeof(OTHER_BAD_CD), 0);
        return;
    }
    printf("sent stuff\n");
    int free_spot = -1;
    for (int i = 0; i < MAXCLIENTS; i++)
        if (!clients[i]) free_spot = i;

    printf("filtered through clients and got free spot %d\n", free_spot);
    if (free_spot == -1) {
        printf("didn't find free spot :(\n");
        send(socket, (void*)TOO_MANY_CD, sizeof(TOO_MANY_CD), 0);
        pthread_mutex_unlock(&clients_mutex);
        return;
    }
    printf("found free spot %d for client %d", free_spot, socket);
    clients[free_spot] = (struct client*) calloc(1, sizeof(struct client));
    if (clients[free_spot] == NULL) {
        send(socket, (void*)OTHER_BAD_CD, sizeof(OTHER_BAD_CD), 0);
        pthread_mutex_unlock(&clients_mutex);
        return;
    }
    curr_cl = clients[free_spot];

    if (recv(socket, curr_cl->username, sizeof(curr_cl->username), 0) < 0) {
        send(socket, (void*)OTHER_BAD_CD, sizeof(OTHER_BAD_CD), 0);
        pthread_mutex_unlock(&clients_mutex);
        return;
    }

    // Subscribe client to #ALL automatically
    curr_cl->subs[0] = "#ALL";

    if (send(socket, (void*)ALL_GOOD_CD, sizeof(ALL_GOOD_CD), 0) < 0) {
        printf("send() for final all good failed\n");
        send(socket, (void*)OTHER_BAD_CD, sizeof(OTHER_BAD_CD), 0);
        pthread_mutex_unlock(&clients_mutex);
        return;
    }
    printf("\taccepted new client %s and now listening\n", curr_cl->username);
    pthread_mutex_unlock(&clients_mutex);
    return;
}

void DieWithError(char* errorMessage) {
    fprintf(stderr, "Dying with error sadface: %s\n", errorMessage);
    exit(1);
}

这是 Makefile

# the compiler: gcc for C
CC = gcc

# compiler flags
CFLAGS = -g

make: ttweetcl.c ttweetsrv.c
    gcc -o ttweetcli ttweetcl.c && gcc -o ttweetsrv ttweetsrv.c -lpthread

.PHONY: clean
clean:
    rm -f ./ttweetcli ./ttweetsrv

【问题讨论】:

  • 你解锁过clients_mutex吗?如果handle_client 主要用作关键部分,那么使用多个线程不会有太大帮助。
  • @yano 我知道我只是没有展示它。 handle_client 唯一的关键部分是它确定我们是否可以持有客户端。如果可以的话,我们会先完成连接设置并解锁clients_mutex,然后再听取他们的意见。
  • ,不能很好地使用goto IMO..你可以用continue;替换第一个goto begin;,然后去掉begin:和第二个@987654335 @ 并具有相同的功能。
  • 很抱歉,但我不确定您希望我们对此做什么。您似乎省略了一些最有可能与问题相关的部分。请提供一个善意 minimal reproducible example 来证明问题。也许这不需要比您已经介绍的更多。
  • @JohnBollinger 我添加了更多代码;现在可以验证了吗?我在我的机器上运行了完全相同的代码,它产生了错误的结果。感谢您的帮助。

标签: c multithreading sockets


【解决方案1】:

解决了!一条评论(现已删除)注意到我没有以\n 结束我的printf(),因此没有刷新缓冲区。现在我已经添加了所有的\n,那么代码就可以正常执行了。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-03-16
    • 2012-09-07
    • 2011-04-12
    • 1970-01-01
    • 2013-10-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多