#include "stdafx.h"
#include <WINSOCK2.H>
#include <iostream>
#pragma comment(lib,"WS2_32.lib")
#define BUF_SIZE 64
int _tmain(int argc, _TCHAR* argv[])
{
//声明变量
WSADATAwsd;
SOCKETsServer;
SOCKETsClient;
intretVal;
charbuf[BUF_SIZE];
//初始化Socket环境
if(WSAStartup(MAKEWORD(2,2),&wsd)!= 0){
printf("WSAStratupfailed !\n");
return1;
}
//创建用于监听的Socket
sServer= socket(AF_INET,SOCK_STREAM,IPPROTO_TCP);
if(INVALID_SOCKET== sServer){
printf("socketfailed !\n");
WSACleanup();
return-1;
}
//设置服务器Socket地址
SOCKADDR_INaddrServ;
addrServ.sin_family= AF_INET;
addrServ.sin_port= htons(9990);
addrServ.sin_addr.S_un.S_addr= htonl(INADDR_ANY);
//绑定Socket Server到本地地址
retVal= bind(sServer,(const struct sockaddr*)&addrServ,sizeof(SOCKADDR_IN));
if(SOCKET_ERROR== retVal){
printf("bindfailed !\n");
closesocket(sServer);
WSACleanup();
return-1;
}
//在Socket Server上进行监听
retVal= listen(sServer,1);
if(SOCKET_ERROR== retVal){
printf("listenfailed !\n");
closesocket(sServer);
WSACleanup();
return-1;
}
//接受来自客户端的请求
printf("TCPServer start......\n");
sockaddr_inaddrClient;
intaddrClientlen = sizeof(addrClient);
sClient= accept(sServer,(sockaddr FAR*)&addrClient,&addrClientlen);
if(INVALID_SOCKET== sClient){
printf("acceptfailed !\n");
closesocket(sServer);
WSACleanup();
return-1;
}
//在服务器与客户端之间发送和接收数据
//循环接收客户端的数据,直到客户端发送quit命令后退出
while(true){
ZeroMemory(buf,BUF_SIZE);
retVal= recv(sClient,buf,BUFSIZ,0);
if(SOCKET_ERROR== retVal){
printf("recvfailed !\n");
closesocket(sServer);
closesocket(sClient);
WSACleanup();
return-1;
}
//获取当前系统时间
SYSTEMTIMEst;
GetLocalTime(&st);
charsDateTime[30];
sprintf_s(sDateTime,
"%4d-%2d-%2d%2d:%2d:%2d",st.wYear,st.wMonth,st.wDay,st.wHour,st.wMinute,st.wSecond);
//打印输出的信息
printf("%s,RecvFrom Client [%s:%d] :%s\n",
sDateTime,inet_ntoa(addrClient.sin_addr),addrClient.sin_port,buf);
//如果客户端发送“quit”字符串,则服务器退出
if(strcmp(buf,"quit")== 0){
retVal= send(sClient,"quit",strlen("quit"),0);
break;
}else{ //否则向客户端发送回显字符串
charmsg[BUF_SIZE];
sprintf_s(msg,"Messagereceived - %s",buf);
retVal= send(sClient,msg,strlen(msg),0);
if(SOCKET_ERROR== retVal){
printf("sendfailed !\n");
closesocket(sServer);
closesocket(sClient);
WSACleanup();
return-1;
}
}
}
//释放资源
closesocket(sServer);
closesocket(sClient);
WSACleanup();
//暂停,按任意键退出
system("pause");
return0;
}