socket新手 求助!
刚在学unix网络编程 connect能够连接 read老是返回-1是什么鬼。客户端代码:
#include <stdio.h>
#include <io.h>
#include <winsock2.h>
int main()
{
int sockfd, n, ret;
WORD ver;
WSADATA data;
ver = MAKEWORD( 2, 2 );
ret = WSAStartup( ver, &data );
char recvline[100], addr[] = "127.0.0.1";
struct sockaddr_in servaddr;
if((sockfd = socket(AF_INET, SOCK_STREAM, 0)) < 0)
{
printf("sock open error!\n");
return 0;
}
memset(&servaddr, 0, sizeof(servaddr));
servaddr.sin_family = AF_INET;
servaddr.sin_port = htons(1111);
servaddr.sin_addr.S_un.S_addr = inet_addr(addr);
if((ret = connect(sockfd, (struct sockaddr*)&servaddr, sizeof(servaddr))) < 0)
{
ret = WSAGetLastError();
printf("connect error!");
return 0;
}
while((n = read(sockfd, recvline, 100)) > 0)
{
recvline[n] = 0;
printf(recvline);
}
if(n < 0)
perror("read");
getchar();
return 0;
}
服务端:
#include <stdio.h>
#include <io.h>
#include <winsock2.h>
#include <time.h>
int main()
{
int listfd, ret, connfd;
time_t ticks;
WORD ver;
WSADATA data;
ver = MAKEWORD( 2, 2 );
ret = WSAStartup( ver, &data );
char sendline[100];
struct sockaddr_in listaddr;
if((listfd = socket(AF_INET, SOCK_STREAM, 0)) < 0)
{
printf("socket open error!");
return 0;
}
memset(&listaddr, 0, sizeof(listaddr));
listaddr.sin_family = AF_INET;
listaddr.sin_port = htons(1111);
listaddr.sin_addr.S_un.S_addr = htonl(INADDR_ANY);
bind(listfd, (struct sockaddr *)&listaddr, sizeof(listaddr));
listen(listfd, 5);
for( ; ; )
{
connfd = accept(listfd, (struct sockaddr *)NULL, NULL);
ticks = time(NULL);
snprintf(sendline, sizeof(sendline), "%.24s\r\n", ctime(&ticks));
write(connfd, sendline, strlen(sendline));
close(connfd);
}
return 0;
}