Linux socket编程-最简单的服务器和客户端程序

复习了一下Linux socket编程,写了最简单的服务器和客户端程序,测试通过,其中服务器端程序采用循环忙等待,后面会改成多线程及线程池机制

服务器端程序

#include <cstdlib>
#include <iostream>
#include <cstring>
#include <cstdio>
#include <cerrno>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <string>

using namespace std;
#define BACKLOG 10

int main(int argc, char * argv[]){
	int connfd, sockfd;
	struct sockaddr_in servaddr;
	struct sockaddr_in tempaddr;
	struct sockaddr_in cliaddr;
	socklen_t clilen;
	char ip_str[INET_ADDRSTRLEN];
	int ret_val;
	
	socklen_t templen;
	sockfd = socket(AF_INET, SOCK_STREAM, 0);
	if(sockfd == -1){
		perror("socket");
		exit(1);
	}

	bzero(&servaddr, sizeof(servaddr));
	servaddr.sin_family = AF_INET;
	servaddr.sin_addr.s_addr = htonl(INADDR_ANY);
	servaddr.sin_port = 0;
	
	ret_val = bind(sockfd,(struct sockaddr *)&servaddr, sizeof(servaddr));
	if(ret_val == -1){
		perror("bind");
		exit(1);
	}
	cout<< "the sockfd is "<< sockfd << endl;
	ret_val = listen(sockfd,BACKLOG);
	if(ret_val == -1){
		perror("listen");
		exit(1);
	}

	templen = sizeof(struct sockaddr);
	ret_val =  getsockname(sockfd, (struct sockaddr *)&tempaddr, &templen);
	if(ret_val == -1){
		perror("getsockname");
		exit(1);
	}

	cout<<"Server is listening on port "<< ntohs(tempaddr.sin_port)<<endl;
	for(;;){
		clilen = sizeof(cliaddr);
		connfd = accept(sockfd,(struct sockaddr *) &cliaddr,&clilen);
		if(connfd == -1){
			perror("accept");
			continue;
		}
		cout<< " Sever: client "<< inet_ntoa(cliaddr.sin_addr) << " connect"<<endl;
		close(connfd);
	}
	return 0;
}


客户端程序

#include <cstdlib>
#include <cstdio>
#include <cstring>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <unistd.h>

#include <iostream>
using namespace std;

int main(int argc, char * argv[]){
	int sockfd;
	int conn_ret;
	struct sockaddr_in servaddr;
	if(argc != 3){
		cout<< "Usage : client <address> <port> " <<endl;
		return 0;
	}
	sockfd = socket(AF_INET,SOCK_STREAM,0);
	if (sockfd == -1){
		perror("sock");
		exit(1);
	}

	bzero(&servaddr,sizeof(servaddr));
	servaddr.sin_family = AF_INET;
        servaddr.sin_port = htons(atoi(argv[2]));
	inet_pton(AF_INET,argv[1],&servaddr.sin_addr);
	conn_ret = connect(sockfd, (struct sockaddr *)&servaddr,sizeof(servaddr));
	if(conn_ret == -1){
		perror("connect");
	}
	close(sockfd);
	return 0;
}


 

你可能感兴趣的:(编程,linux,socket,struct,Stream,服务器)