一个小程序,实现服务器&客户机的通信,当有客户请求连接时,在端口5050于客户端进行tcp连接,连接成功显示客户IP&端口号,并给客户发一条信息。
服务器程序没有问题,客户机程序编译时提示fatal error C1004: unexpected end of file found
服务器程序:
#include<Winsock2.h>
#include<stdio.h>
#include<stdlib.h>
#define DEFAULT_PORT 5050
void main()
{
int iPort=DEFAULT_PORT;
WSADATA wsaData;
SOCKET sListen,sAccept;
int iLen;
int iSend;
char buf[]="I am a server.";
struct sockaddr_in ser,cli;
printf("-----------\n");
printf("Server waiting\n");
if(WSAStartup(MAKEWORD(2,2),&wsaData)!=0)
{
printf("Failed to load Winsock.\n");
return;
}
sListen=socket(AF_INET,SOCK_STREAM,0);
if(sListen==INVALID_SOCKET)
{
printf("socket()Failed:%d\n",WSAGetLastError());
return;
}
ser.sin_family=AF_INET;
ser.sin_port=htons(iPort);
ser.sin_addr.s_addr=htonl(INADDR_ANY);
if(bind(sListen,(LPSOCKADDR)&ser,sizeof(ser))==SOCKET_ERROR)
{
printf("bind()Faild:%D\n",WSAGetLastError());
return;
}
if(listen(sListen,5)==SOCKET_ERROR)
{
printf("listen()FAILED:%d\n",WSAGetLastError());
return;
}
while(1)
{
sAccept=accept(sListen,(struct sockaddr*)&cli,&iLen);
if(sAccept==INVALID_SOCKET)
{
printf("accept()Failed:%d\n",WSAGetLastError());
break;
}
printf("Accepted client IP:[%s],port:[%d]\n",inet_ntoa(cli.sin_addr),ntohs(cli.sin_port));
iSend=send(sAccept,buf,sizeof(buf),0);
if(iSend==SOCKET_ERROR)
{
printf("send()Failed:%d\n",WSAGetLastError());
break;
}
else if(iSend==0)
break;
else
{
printf("send()byte:%d\n",iSend);
printf("----------\n");
}
closesocket(sAccept);
}
closesocket(sListen);
WSACleanup();
}
客户机程序
#include<Winsock2.h>
#include<stdio.h>
#define DEFAULT_PORT 5050
#define DATA_BUFFER 1024
void main(int argc,char *argv[])
{
WSADATA wsaData;
SOCKET sClient;
int iPort=DEFAULT_PORT;
int iLen;
char buf[DATA_BUFFER];
struct sockaddr_in ser;
if(argc<2)
{
printf("Usage:client[server IP address]\n");
return;
memset(buf,0,sizeof(buf));
if(WSAStartup(MAKEWORD(2,2),&wsaData)!=0)
{
printf("Failed to load Winsock.\n");
return;
}
ser.sin_family=AF_INET;
ser.sin_port=htons(iPort);
ser.sin_addr.s_addr=inet_addr(argv[1]);
sClient=socket(AF_INET,SOCK_STREAM,0);
if(sClient==INVALID_SOCKET)
{
printf("socket()Failed:%d\n",WSAGetLastError());
return;
}
if(connect(sClient,(struct sockaddr*)&ser,sizeof(ser))==INVALID_SOCKET)
{
printf("connect() Failed:%d\n",WSAGetLastError());
return;
}
else
{
iLen=recv(sClient,buf,sizeof(buf),0);
if(iLen==0)
return;
else if(iLen==SOCKET_ERROR)
{
printf("recv() Failed:%d\n",WSAGetLastError());
return;
}
printf("recv() data from server:%s\n",buf);
}
closesocket(sClient);
WSACleanup();
}