Linux 树莓派上简单的网络编程程序实现

客户端程序,向服务器发送helloworld消息

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




int main()
{

    int client_sockfd = -1;                           //创建套接字
	
	struct sockaddr_in server_addr; 				 //服务器端网络地址结构体  
	memset(&server_addr,0,sizeof(server_addr)); 	 //数据初始化--清零  
	server_addr.sin_family = AF_INET;				 
	server_addr.sin_addr.s_addr = inet_addr("127.0.0.1");  	 //服务器IP地址 
	server_addr.sin_port = htons(8000);
	
	if(-1 == (client_sockfd = socket(AF_INET,SOCK_STREAM,0)))  
	{    
		return -1;  
	}  
	if(-1 == (connect(client_sockfd,(struct sockaddr *)&server_addr,sizeof(struct sockaddr))))
	{
		return -1;
	}
	send(client_sockfd,"helloworld",sizeof("helloworld"),0);
	close(client_sockfd);//关闭套接字
		
}

服务端接收程序

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

#define BUFFERSIZE 1024
int main(int argc,char **argv)
{
	int listenfd,connfd;
	
	struct sockaddr_in sockaddr;
	char buff[BUFFERSIZE];
	int n;

	memset(&sockaddr,0,sizeof(sockaddr));

	sockaddr.sin_family = AF_INET;
	sockaddr.sin_addr.s_addr = htonl(INADDR_ANY);   //绑定本机网卡
	sockaddr.sin_port = htons(8000);

	listenfd = socket(AF_INET,SOCK_STREAM,0);

	if(-1 == bind(listenfd,(struct sockaddr *) &sockaddr,sizeof(sockaddr)))
	{
		printf("bind error");
	}
	listen(listenfd,1024);

	while(1)
	{
		 if((connfd = accept(listenfd,(struct sockaddr*)NULL,NULL))==-1)
		 {
			 printf("accpet socket error: %s errno :%d\n",strerror(errno),errno);
			 continue;
		 }
		 
			 n = recv(connfd,buff,BUFFERSIZE,0);
			 buff[n] = '\0';
			 printf("recv msg from client:%s\n",buff);
			 close(connfd);
	}
	 close(listenfd);
	
}











你可能感兴趣的:(Linux,树莓派学习笔记)