Server can't read all messages from client?

时间:2015-07-08 15:44:08

标签: c sockets client-server

In this program I am trying to send 10 messages (C 0, C 1, D 2 ... C 9) from client_A to the server. I have edited this question as I've been advised by other users. Now the code handles all errors could possibly caused by the system calls, also I fixed a lot of bugs. I am facing a situation where is no error generated by any system call. the program reads the first message, print the number of bytes it read (200) and then shows that there is "No such file or directory", and prints the number of the loop at which it stopped.

This is the part of the code where the program listens and reads from the socket:

//accept connections  
tv.tv_sec = 0;
tv.tv_usec = 0;
for (i = 0; i < ns; i++) { //ns=1
   len = sizeof(who);
   sc[i] = accept (ls, (struct sockaddr *) &who, &len);
   if(sc[i] < 0)
      perror("Faild to accept socket - in server_process");

   n[i] = 1;
}

//select connections and read from sockets
i = 0;
while(i < 10) {
  FD_ZERO(&rmask);
  for (j = 0; j < ns; j++) {
     if (n[j] > 0) {
        FD_SET(sc[j], &rmask);
     }
  }
  select (32, &rmask, NULL, NULL, &tv);
  for (j = 0; j < ns; j++) {
    if ((FD_ISSET(sc[j], &rmask))){ 
        if ((n[j] = read(sc[j], buf, max)) > 0) {
          time (&now);
          printf ("\n $d bytes read. %s %s", n[j], buf, ctime (&now));
          i++;
        }else{
          perror("Faild to read socket - in server_process");
          exit(1);
        }
    }//if
  }//for
}

//close all connections
close(ls);
for (i = 0; i < ns; i++) {
  close (sc[i]);
}

And this is the part of the code where the program write into the socket:

for (i = 0; i < 10; i++) {
   x = (rand() % 2);
   if (x == 1)
      ch = 'C';
   else
      ch = 'D';

   sprintf(msgbuf, "Message from A: %c %d", ch, i);
   printf("before wirte to socket!");
   wr = write(s, msgbuf, strlen (msgbuf) + 1);
   if (wr < 0) {
      perror("Faild to write from client_A - in clientA");
   }   
}

If more code needed to be shown, please let me know. The only output it shows is:

num of bytes: 200 message: Message from A: C 0 Wed Jul 8 18:29:19 2015

Faild to read socket - in server_process: No such file or directory

2

1 个答案:

答案 0 :(得分:4)

TCP does not support messages. It provides a boundaryless stream of bytes. You have not made use of the return value of read to find out how many bytes you actually got. You assumed that each read will return one application message which is not so.

相关问题