我正在編寫一個客戶端,以使用LINUX上的C腳本讀取TCP下通過套接字從服務(wù)器發(fā)送回的數(shù)據(jù)。該服務(wù)器永遠(yuǎn)運行,我驗證是否可以得到答復(fù)netcat localhost [PORT_NUMBER]。使用以下命令檢查時,服務(wù)器處于LISTEN狀態(tài)netstat -naprecv()函數(shù)返回預(yù)期的字節(jié)數(shù),但是buffer變空并且strlen(buffer)為0。我還嘗試更改為read(),這沒想到會有不同的結(jié)果,并且顯示了相同的問題。這是代碼。#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);感謝您的幫助。我是套接字編程的新手,無法跟蹤發(fā)生了什么。PS。答復(fù)的預(yù)期字節(jié)大小為1108,這是正確的。我打算將最大大小設(shè)為1200,以確認(rèn)接收到正確的字節(jié)數(shù)。PS2。也請隨時對低級c的編碼風(fēng)格進(jìn)行評論。
添加回答
舉報
0/150
提交
取消