第1个回答 2011-04-21
//获取时间
CString strTime;
CTime st = CTime::GetCurrentTime();
strTime = st.Format("%Y%m%d%H%M%S");
//创建服务器端
WORD wVersionRequested;
WSADATA wsaData;
int err;
wVersionRequested = MAKEWORD( 1, 1 );
err = WSAStartup( wVersionRequested, &wsaData );
if ( err != 0 ) {
return;
}
if ( LOBYTE( wsaData.wVersion ) != 1 ||
HIBYTE( wsaData.wVersion ) != 1 ) {
WSACleanup( );
return;
}
SOCKET sock = socket(AF_INET,SOCK_STREAM,0);
int opt = 1;
int len11 = sizeof(opt);
setsockopt(sock,SOL_SOCKET,SO_REUSEADDR,(char*)&opt,len11);
if (sock == INVALID_SOCKET)
{
// "初始化失败" ;
closesocket(sock);
return;
}
SOCKADDR_IN addrsrv;
addrsrv.sin_family = AF_INET;
addrsrv.sin_port = htons(6001);
addrsrv.sin_addr.S_un.S_addr = htonl(INADDR_ANY);
if (bind(sock,(SOCKADDR*)&addrsrv,sizeof(SOCKADDR)) == SOCKET_ERROR)
{
// "绑定失败"
closesocket(sock);
return;
}
listen(sock,10);
//客户端接收服务器连接
char m_recvBuf[2000];
memset(m_recvBuf, 0, 2000);
while(TRUE)
{
SOCKET sNew = ::accept(sock, (SOCKADDR*)&addrRemote, &nAddrLen);//接收到客户端连接
//发送时间
int hvsndlen = 0;
int sndlen = 0;
while ((len -hvsndlen) > 0)
{
sndlen = send(soc,(LPCTSTR)strTime +hvsndlen,len-hvsndlen,0);
if (sndlen == SOCKET_ERROR)
{
return -1;
}
hvsndlen += sndlen;
}
}
//把以上程序放入你的主程序中,应该可以运行。里面有CString类型,如果用不习惯,你可以把CTime 转换成其他类型本回答被提问者和网友采纳