简体   繁体   中英

Server doesn't read message from client

I'm trying to implement a simple multi-threaded client/server program: the client sends the server a number and the server creates a thread that sends back the number+1.

The problem is as follows: The client connects to the server with no problems; The thread is (as far as i can tell) created without issues; But after the client writes the number in the socket, the server simply doesn't see it. The call to read() gives no errors, it just sits there, waiting forever.

I tried sending more than one integer through it; no difference. A suspicion i have is that the file descriptor server-side is passed incorectly to the thread,but i can't figure out how. Another suspicion i have is that i am missing something stupidly obvious.

Either way, help is appreciated. Any ideas?

Server-side: the loop that creates threads.

    while (1) {

    int client;

    printf("[server]Waiting at port %d...\n", PORT);
    fflush(stdout);

    int length = sizeof(from);
    if (client = accept(sd, (struct sockaddr*)&from, &length) < 0) {
        perror("[server]Error: accept().");
        continue;
    }

    pthread_t th_id;
    pthread_create(&th_id, NULL, &treat, &client);

    }

Server-side: thread's treat function (the problem is here).

void* treat(void* client)
{

printf("[thread]Waiting for message...\n");
fflush(stdout);
pthread_detach(pthread_self());

int client_sd = *((int*)client);

int nr;
if (read(client_sd, &nr, sizeof(int))) {
    perror("[thread]Error: read().");
    exit(-1);
}
// The program won't reach this point.
printf("[thread]Read: %d", nr);
fflush(stdout);

close(*((int*)client));
return (NULL);

}

Client-side:

      if (connect (sd, (struct sockaddr *) &server,sizeof (struct sockaddr)) == -1)
    {
      perror ("[client]Error: connect().\n");
      return errno;
    }

  printf ("[client]Write a number: ");
  fflush (stdout);

  scanf("%d",&nr);

  printf("[client] Read %d\n",nr);

  if (write (sd,&nr,sizeof(int)) <= 0)
    {
      perror ("[client]Error: write()\n");
      return errno;
    }

    //the program reaches here.
  printf("[client]The message was sent\n");

The problem is at line

if (client = accept(sd, (struct sockaddr*)&from, &length) < 0) {

it is interpreted as

if (client = (accept(sd, (struct sockaddr*)&from, &length) < 0)) {

and if accept returns positive then the client is set to 0 . Subsequent read in the thread is read from stdin then.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM