我们物联网专业的嵌入式实习-day06(开发智能家居系统-网络编程)

 今天的学习内容在我上传的资源里面
我提供下链接供参考
http://download.csdn.net/download/lsy888520/10125386


相关代码 

soc1.c


#include
#include
#include
#include
#include
#include


int main()
{
//serve
//


//socket
//


int socketFd = socket(PF_INET, SOCK_STREAM, 0);
if(socketFd < 0)
{
perror("socket error ! \n");
return -1;
}
printf("socket ok !\n");


//bind
//
struct sockaddr_in serverAddr;
memset(&serverAddr, 0, sizeof(serverAddr));
serverAddr.sin_family = PF_INET;
serverAddr.sin_port = htons(8888);
serverAddr.sin_addr.s_addr = inet_addr("192.168.1.131");
int bindRet = bind(socketFd, (struct sockaddr*)&serverAddr, sizeof(serverAddr));
if(bindRet < 0)
{
perror("bind error !");
return -1;
}
printf("bind ok !\n");


//listen
//
bindRet = listen(socketFd, 10);
if(bindRet < 0)
{
perror("listen error !");
return -1;
}
printf("listening.........\n");


//accept
//
int connFd = accept(socketFd, NULL, NULL);
if(connFd < 0)
{
perror("accept error !");
return -1;
}
printf("accept ok !\n");


//send\rec
//
while(1)
{


char buf[1024] = {0};
recv(connFd, buf, sizeof(buf), 0);
printf("recv from client : %s\n", buf);


sleep(2);
memset(buf, 0, sizeof(buf));
strcpy(buf, "i am serve !");
// buf[1024] = "i am serve!";


send(connFd, buf, sizeof(buf), 0);
}
//close
//
close(connFd);
close(socketFd);


return 0;
}


cli2.c


#include
#include
#include
#include
#include
#include


int main()
{
//client
//
//socket
//
int clientFd = socket(PF_INET, SOCK_STREAM, 0);
if(clientFd < 0)
{
perror("socket error !");
return -1;
}
printf("socket ok !\n");
 
//connect
//
struct sockaddr_in servAddr;
memset(&servAddr, 0, sizeof(servAddr));
servAddr.sin_family = PF_INET;
servAddr.sin_port = htons(8888);
servAddr.sin_addr.s_addr = inet_addr("192.168.1.131");
int connFd = connect(clientFd, (struct sockaddr *)&servAddr, sizeof(servAddr));
if(connFd < 0)
{
perror("connect error !");
return -1;
}
printf("connect ok !\n");




//send
//
while(1)
{



char buf[1024] = "hello two dog child!";
send(clientFd, buf, sizeof(buf), 0);
memset(buf, 0, sizeof(buf));

sleep(2);
recv(clientFd, buf, sizeof(buf), 0);
printf("recv from socket : %s\n", buf);


}
//close
//
close(clientFd);


return 0;


}






你可能感兴趣的:(我们物联网专业的嵌入式实习-day06(开发智能家居系统-网络编程))