客户端程序:
#include
#include
void main()
{
//加载套接字库
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 sockClient = socket (AF_INET,SOCK_STREAM,0);
SOCKADDR_IN addrSrv;
addrSrv.sin_addr.S_un.S_addr = inet_addr("192.168.1.2");
addrSrv.sin_family = AF_INET;
addrSrv.sin_port = htons (6000);
//向服务器发出连接请求
connect(sockClient,(SOCKADDR*)&addrSrv,sizeof(SOCKADDR));
//接收数据
char data='0';
int time=120;
do {
recv(sockClient,&data,sizeof(char),0);
//发送数据
if(data=='1')
{
printf("data=%c ",data);
data='0';
send(sockClient,&data,sizeof(char),0);
}
printf("data=%c ",data);
Sleep(1000);
} while(time);
closesocket(sockClient);
WSACleanup();
}
服务器端程序:
#include
#include
void main()
{
//加载套接字库
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 sockSrv = socket (AF_INET,SOCK_STREAM,0);
SOCKADDR_IN addrSrv;
addrSrv.sin_addr.S_un.S_addr = htonl (INADDR_ANY);
addrSrv.sin_family = AF_INET;
addrSrv.sin_port = htons(6000);
//绑定套接字
bind(sockSrv,(SOCKADDR*)&addrSrv,sizeof(SOCKADDR));
//将套接字设为监听模式,准备接受客户请求
listen(sockSrv,5);
SOCKADDR_IN addrClient;
int len = sizeof(SOCKADDR);
char data='1';
SOCKET sockConn = accept(sockSrv,(SOCKADDR*)&addrClient,&len);
while(1)
{
//发送数据
send(sockConn,&data,sizeof(char),0);
//接收数据
recv(sockConn,&data,sizeof(char),0);
if(data=='0')
{
printf("data=%c ",data);
data='1';
}
}
closesocket(sockConn);
// }
}
阅读(1239) | 评论(0) | 转发(0) |