我正在编写一个客户端,以使用LINUX上的C脚本读取TCP下通过套接字从服务器发送回的数据。该服务器永远运行,我验证是否可以得到答复netcat localhost [PORT_NUMBER]。使用以下命令检查时,服务器处于LISTEN状态netstat -naprecv()函数返回预期的字节数,但是buffer变空并且strlen(buffer)为0。我还尝试更改为read(),这没想到会有不同的结果,并且显示了相同的问题。这是代码。#include <stdio.h>#include <string.h> //strlen#include <sys/socket.h>#include <arpa/inet.h> //inet_addr#include <unistd.h>#include <stdlib.h>int main(int argc, char *argv[]){ int socket_desc, msg_rep_size = 1200, msg_size = 100; struct sockaddr_in server; char message[msg_size], server_reply[msg_rep_size]; //Create socket socket_desc = socket(AF_INET, SOCK_STREAM, 0); if (socket_desc == -1) { printf("Could not create socket"); } server.sin_addr.s_addr = inet_addr("0.0.0.0"); server.sin_family = AF_INET; server.sin_port = htons(31114); // PORT_NUMBER //Connect to remote server if (connect(socket_desc, (struct sockaddr *)&server, sizeof(server)) < 0) { printf("connect error"); return 1; } printf("Connected"); while (1) { // send some data bzero(message, msg_size); strncpy(message, "REQUEST\n", msg_size); if (send(socket_desc, message, msg_size, 0) < 0) { printf("Send failed"); return 1; } printf("Data Send\n"); // Receive a reply from the server bzero(server_reply, msg_rep_size); int read_result = recv(socket_desc, server_reply, msg_rep_size, 0); if (read_result < 0) { printf("Receive failed\n"); return 1; } else { printf("Reply received\n"); printf("read_result: %d\n", read_result); printf("strlen(server_reply): %d\n", (int)strlen(server_reply)); printf("Reply: %s\n", server_reply); } usleep(8);}return 0;}如果我从int read_result = recv(socket_desc, server_reply, msg_rep_size, 0); 至int read_result = read(socket_desc, server_reply, msg_rep_size);感谢您的帮助。我是套接字编程的新手,无法跟踪发生了什么。PS。答复的预期字节大小为1108,这是正确的。我打算将最大大小设为1200,以确认接收到正确的字节数。PS2。也请随时对低级c的编码风格进行评论。
1 回答
- 1 回答
- 0 关注
- 364 浏览
添加回答
举报
0/150
提交
取消