用C语言实现socket通信为什么连接成功但send recv都返回-1呀???
第一次接触,很简单的程序~想了好久呀代码如下:
/*serve.c*/
#include <stdio.h>
#include <winsock2.h>
#define SERVER_PORT 6666
#pragma comment(lib, "ws2_32.lib")
main()
{ int serversock,new_sock,addrlen;
char ch[20]={"Hello world"};
SOCKADDR_IN serveraddr,clientaddr;
WSADATA wsadata;
WSAStartup(MAKEWORD(2,1), &wsadata);
if((serversock=socket(AF_INET,SOCK_STREAM,0))<0)
{printf("can not create a socket\n");
exit(1);
}
serveraddr.sin_family = AF_INET;
serveraddr.sin_port = htons(SERVER_PORT);
serveraddr.sin_addr.S_un.S_addr = htonl(INADDR_ANY);
if(bind(serversock,(SOCKADDR*)&serveraddr,sizeof(serveraddr))<0)
{printf("can not bind\n");
exit(1);
}
printf("listening...\n");
listen(serversock,1);
addrlen=sizeof(serveraddr);
printf("waiting...\n");
if(new_sock=accept(serversock,(SOCKADDR*)&clientaddr,&addrlen)<0)
{printf("can not accept\n");
exit(1);
}
while(1)
{printf("connected and sending...\n");
if (send(serversock,ch,20,0)<0)
{printf("can not send\n");
break;
}
printf("sended\n");}
closesocket(new_sock);
}
/*client.c*/
#include <stdio.h>
#include <winsock2.h>
#define SERVER_PORT 6666
#define SERVER_ADDRESS "59.68.161.199"
#pragma comment(lib, "ws2_32.lib")
main()
{ int clientsock;
char ch[21];
int c;
SOCKADDR_IN serveraddr;
WSADATA wsadata;
WSAStartup(MAKEWORD(2,1), &wsadata);
if((clientsock=socket(AF_INET,SOCK_STREAM,0))<0)
{printf("can not create a socket\n");
exit(1);
}
serveraddr.sin_family = AF_INET;
serveraddr.sin_port = htons(SERVER_PORT);
serveraddr.sin_addr.S_un.S_addr = inet_addr(SERVER_ADDRESS);
printf("connecting...\n");
c=connect(clientsock,(SOCKADDR*)&serveraddr,sizeof(serveraddr));
if(c<0)
{printf("can not connect\n");
exit(1);
}
while(1)
{printf("getting\n");
if((recv(clientsock,ch,21,0))<0)
{printf("can not receive\n");
break;
}
printf("GOT:%s\n",ch);
}
closesocket(clientsock);
}