[問題] 如何使用TCPSERVER印出完整資料 ??

看板C_and_CPP (C/C++)作者 (Elaker)時間10年前 (2015/11/18 15:33), 編輯推噓1(102)
留言3則, 2人參與, 最新討論串1/1
開發平台(Platform): Fedora , C 問題(Question): 00000000 | 30 31 30 31 00 00 00 00 | 0 1 0 1 . . . . 00000010 | 30 30 30 30 00 00 00 00 | 0 0 0 0 . . . . 以上是餵給SERVER的資料,想要的資料是第二行的 0 0 0 0 但每次都只印出 0 1 0 1,想請問各位怎樣才能全部印出 ?? 朋友問我但我也不是很了解,所以請各位大大解惑,謝謝。 程式碼(Code): #include <stdio.h> #include <sys/types.h> #include <sys/socket.h> #include <netinet/in.h> #include <sys/errno.h> #define SERV_PORT 60000 #define MAXNAME 1024 extern int errno; main() { int socket_fd; /* file description into transport */ int recfd; /* file descriptor to accept*/ int length; /* length of address structure*/ int nbytes; /* the number of read */ char buf[BUFSIZ]; struct sockaddr_in myaddr; /* address of this service */ struct sockaddr_in client_addr; /* address of client */ /* Get a socket into TCP/IP */ if ((socket_fd = socket(AF_INET, SOCK_STREAM, 0)) <0) { perror ("socket failed"); exit(1); } /*Set up our address*/ bzero ((char *)&myaddr, sizeof(myaddr)); myaddr.sin_family = AF_INET; myaddr.sin_addr.s_addr = htonl(INADDR_ANY); myaddr.sin_port = htons(SERV_PORT); /* Bind to the address to which the service will be offered*/ if (bind(socket_fd, (struct sockaddr *)&myaddr, sizeof(myaddr)) <0) { perror ("bind failed"); exit(1); } /* Set up the socket for listening, with a queue length of 5*/ if (listen(socket_fd, 20) <0) { perror ("listen failed"); exit(1); } /* Loop continuously, waiting for connection requests and performing the service*/ length = sizeof(client_addr); printf("Server is ready to receive !!\n"); printf("Can strike Cntrl-c to stop Server >>\n"); while (1) { if ((recfd = accept(socket_fd, (struct sockaddr_in *)&client_addr, &length)) <0) { perror ("could not accept call"); exit(1); } if ((nbytes = read(recfd, &buf, BUFSIZ)) < 0) { perror("read of data error nbytes !"); exit (1); } printf("Create socket #%d form %s : %d\n", recfd, inet_ntoa(client_addr.sin_addr), htons(client_addr.sin_port)); printf("%s\n", &buf); /* return to client */ if (write(recfd, &buf, nbytes) == -1) { perror ("write to client error"); exit(1); } close(recfd); printf("Can Strike Crtl-c to stop Server >>\n"); } } -- ※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 42.73.207.219 ※ 文章網址: https://www.ptt.cc/bbs/C_and_CPP/M.1447832014.A.49C.html

11/18 15:51, , 1F
其實資料應該都有收到, 只是印的時候, 遇到字串結束字元.
11/18 15:51, 1F

11/18 15:55, , 2F
亂改: printf("%s\n", &buf); 改為 printf("%s\n", buf+010);
11/18 15:55, 2F

11/18 16:40, , 3F
再試試看,謝謝~~~
11/18 16:40, 3F
文章代碼(AID): #1MJ2dEIS (C_and_CPP)
文章代碼(AID): #1MJ2dEIS (C_and_CPP)