|
我第一次写socket的程序,在和服务器建立连接后,使用recv接收数据,当没有数据可读时recv会一直在哪里等待,不知道是怎么回事,我是这样调用的啊
recv(s, buffer, 255, 0),应该没有错吧,
为说明问题,附上源码
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#define PORT 21
#define SERVER_IP "61.129.102.193"
int main()
{
struct sockaddr_in addr;
char buffer[256],command[256];
int s,i;
memset(buffer, 0, sizeof(buffer));
memset(command, 0, sizeof(command));
if ((s=socket(AF_INET, SOCK_STREAM, 0)) < 0) //建立一个socket
{
printf("failed to create socket!\n");
exit(1);
}
bzero(&addr, sizeof(addr));
addr.sin_family = AF_INET;
addr.sin_port = htons(PORT);
addr.sin_addr.s_addr = inet_addr(SERVER_IP);
if (connect(s, (const struct sockaddr*)&addr, sizeof(addr))<0)
{
printf("failed to connect server!\n");
exit(1);
}
memset(buffer, 0, sizeof(buffer));
while (recv(s, buffer, 255, 0)>0)
{
printf("%s", buffer);
memset(buffer, 0, sizeof(buffer));
}
shutdown(s, 2);
return 0;
} |
|