我一直在尝试使用以下代码从客户端接收服务器套接字上的数据,
服务器.c
int startServer(uint16_t myPort)
{
int listenFd = 0, connfd = 0;
struct sockaddr_in serv_addr;
listenFd = socket(AF_INET, SOCK_STREAM, 6);
if (listenFd == -1) {
perror("socket");
return EXIT_FAILURE;
}
memset(&serv_addr, '0', sizeof(serv_addr));
serv_addr.sin_family = AF_INET;
serv_addr.sin_addr.s_addr = htonl(INADDR_ANY);
serv_addr.sin_port = htons(myPort);
if (-1 == bind(listenFd, (struct sockaddr*)&serv_addr, sizeof(serv_addr))) {
perror("bind");
return EXIT_FAILURE;
}
if (-1 == listen(listenFd, 10)) {
perror("listen");
return EXIT_FAILURE;
}
printf("Server listening on %d\n", myPort);
int n = 0, k;
char recvBuff[1024];
struct sockaddr_in conn_addr;
unsigned int len = sizeof(conn_addr);
while(1)
{
connfd = accept(listenFd, (struct sockaddr*)NULL, NULL);
n = recv(connfd, &recvBuff, 1023, 0);
printf("Recd: %d bytes\n",n);
for (k=0; k<16; ++k) { printf("%d: 0x%02X, ", k, recvBuff[k]); }
sleep(1);
}
}
在client.c中
int main(int argc, char *argv[])
{
int sockfd = 0, n = 0;
struct sockaddr_in serv_addr;
if(argc != 2)
{
printf("\n Usage: %s <ip of server> \n",argv[0]);
return 1;
}
if((sockfd = socket(AF_INET, SOCK_STREAM, 0)) < 0)
{
printf("\n Error : Could not create socket \n");
return 1;
}
memset(&serv_addr, '0', sizeof(serv_addr));
serv_addr.sin_family = AF_INET;
serv_addr.sin_port = htons(5000);
if(inet_pton(AF_INET, argv[1], &serv_addr.sin_addr)<=0)
{
printf("\n inet_pton error occured\n");
return 1;
}
if( connect(sockfd, (struct sockaddr *)&serv_addr, sizeof(serv_addr)) < 0)
{
printf("\n Error : Connect Failed \n");
return 1;
}
uint32_t dataVal = 0xa0b0c0d0;
int res = write(sockfd, (void*)&dataVal, sizeof(dataVal));
printf("%d bytes sent\n", res);
close(sockfd);
return 0;
}
但是,有了这个,我看到服务器说它收到了字节,但是打印字节之后的行(在 for 循环中)似乎从未被执行过。有谁知道我在这里做错了什么?