1、基于套接字Socket通信的编程: 建立TCPSocket进行通信,服务器端向客户端传送日期数据,客户端收到信息
1个回答
展开全部
//获取时间
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 转换成其他类型
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 转换成其他类型
本回答被提问者和网友采纳
已赞过
已踩过<
评论
收起
你对这个回答的评价是?
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询