Linux网络编程(二)——多进程并发,通信服务

客户端

#include <stdio.h>
#include <stdlib.h>
#include <WinSock2.h>
#include<io.h>
#include<time.h>
void error(char *er);
#pragma comment(lib, "ws2_32.lib")  //加载 ws2_32.dll
int main(){
	while (1)
	{

	char IP[100];
	int port;
	//初始化DLL
	WSADATA wsaData;
	if (WSAStartup(MAKEWORD(2, 2), &wsaData) != 0)
		error("WSAStartup error!\n");
	//创建套接字
	SOCKET sock = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP);
	//向服务器发起请求
	if (sock == INVALID_SOCKET)
		error("Wrong scoket!\n");
	printf("输入目标IP地址和端口号(ip/网址 port):");
	scanf("%s %d", IP, &port);
	if (!(IP[0] >= 0 && IP[0] <= 9))//输入为域名的情况!
	{
		struct hostent*host;
		host=gethostbyname(IP);
		strcpy(IP, inet_ntoa(*(struct in_addr*)host->h_addr_list[0]));
	}

	sockaddr_in sockAddr;
	memset(&sockAddr, 0, sizeof(sockAddr));  //每个字节都用0填充
	sockAddr.sin_family = PF_INET;
	sockAddr.sin_addr.s_addr = inet_addr(IP);
	sockAddr.sin_port = htons(port);
	//发送命令
	if (connect(sock, (SOCKADDR*)&sockAddr, sizeof(SOCKADDR)) == SOCKET_ERROR)//连接
		error("Connect failed!\n");
	//接收服务器传回的数据
	int len;
	char szBuffer[MAXBYTE] = "It's hard to see you!\n";
	len = recv(sock, szBuffer, MAXBYTE, 0);
	//输出接收到的数据
		if (len > 0)
		printf("\nMessage form server: %s\n", szBuffer);
		char instr[10];
		printf("输入命令:");//snd  与 get
		scanf("%s", instr);
		send(sock, instr, 3, 0);
		if (strcmp(instr, "qui") == 0 || strcmp(instr, "QUI") == 0)
		{
			if ((len = recv(sock, szBuffer, MAXBYTE, 0)) > 0)//易错,记得加上括号!
			{
				szBuffer[len] = '\0';
				printf("\nMessage form server: %s\n", szBuffer);
			}
			closesocket(sock);
			printf("断开成功!\n\n");
			break;
		}
		char basicpath[150] = "C:\\Users\\Administrator\\Desktop\\";
		char filename[50] = { 0 };

		if ((len = recv(sock, szBuffer, MAXBYTE, 0)) > 0)//易错,记得加上括号!
		{
			szBuffer[len] = '\0';
			printf("\nMessage form server: %s\n", szBuffer);
		}	
		if (strcmp(instr, "snd") == 0)//发送文件
		{
			printf("输入文件名:");
			scanf("%s", filename);
			send(sock, filename, strlen(filename) + 1, 0);
			strcat(basicpath, filename);
			FILE*p = fopen(basicpath, "rb+");
			if (p == NULL)printf("FILE *P  error");
			while ((len = fread(szBuffer, 1, MAXBYTE, p)) > 0)
				send(sock, szBuffer, len, 0);
			printf("上传成功!\n\n");
			fclose(p);
		}
		if (strcmp(instr, "get") == 0)//接受文件
		{
			printf("输入文件名:");
			scanf("%s", filename);
			send(sock, filename, strlen(filename) + 1, 0);
			strcat(basicpath, filename);
			FILE*p;
			p = fopen(basicpath, "wb+");
			if (p == NULL)printf("FILE *P  error");
			while ((len = recv(sock, szBuffer, MAXBYTE, NULL)) > 0)
				fwrite(szBuffer, 1, len, p);
			printf("下载成功!\n\n");
			fclose(p);
		}
		shutdown(sock, SD_SEND);
		//关闭套接字
		closesocket(sock);
	}
	//终止使用 DLL
	WSACleanup();
	system("pause");
	return 0;
}
void error(char *er)
{
	printf("%s\n", er);
	exit(1);
}



服务器端

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <arpa/inet.h>
#include <sys/socket.h>
#include <sys/wait.h>
#include <signal.h>
#include <fcntl.h>
#include <time.h>
#define BUF_SIZE 1024
void error_handling(char *message);
void childproc(int sig);
int main(int argc, char *argv[])
{
	struct sigaction act;
	int state;
	act.sa_handler=childproc;
	sigemptyset(&act.sa_mask);
	act.sa_flags=0;
	state=sigaction(SIGCHLD,&act,0);


	int serv_sock, clnt_sock;//预防僵尸进程
	int str_len, i=0;	
	struct sockaddr_in serv_adr;
	struct sockaddr_in clnt_adr;
	socklen_t clnt_adr_sz;
	
	if(argc!=2) {
		printf("Usage : %s <port>\n", argv[0]);
		exit(1);
	}	
	serv_sock=socket(PF_INET, SOCK_STREAM, 0);   
	if(serv_sock==-1)
		error_handling("socket() error");	
	memset(&serv_adr, 0, sizeof(serv_adr));
	serv_adr.sin_family=AF_INET;
	serv_adr.sin_addr.s_addr=htonl(INADDR_ANY);
	serv_adr.sin_port=htons(atoi(argv[1]));
	if(bind(serv_sock, (struct sockaddr*)&serv_adr, sizeof(serv_adr))==-1)
		{error_handling("bind() error");exit(1);}
	while(1)
	{	
	if(listen(serv_sock, 5)==-1)
		{continue;}	
	clnt_adr_sz=sizeof(clnt_adr);
	
	clnt_sock=accept(serv_sock, (struct sockaddr*)&clnt_adr, &clnt_adr_sz);
	if(clnt_sock==-1)
		{continue;}
	else
		printf("\nConnected client %d \n", i++);
	//service
	char buff[BUF_SIZE]="\nHello ,How can I help you!\nYou can send message to us for service:\n\"get\" for downloading a file from us;\n\"snd\" for uploading a file to us!\n\"qui\" or \"QUI\" for quit!\n";
	pid_t pidd;
	pidd=fork();//多进程并发
	if(pidd==-1)
	{
		close(clnt_sock);
		continue;
	}
	if(pidd==0){
	close(serv_sock);
	if(write(clnt_sock,buff,strlen(buff))==-1)
		{error_handling("write() error!\n");close(clnt_sock);continue;}
	if(read(clnt_sock,buff,3)!=3)
		{error_handling("error read!\n");close(clnt_sock);continue;}
	buff[3]='\0';
	//instruction
	if(strcmp(buff,"qui")==0||strcmp(buff,"QUI")==0)
	{
		write(clnt_sock,"close connection!\n",strlen("close connection!\n")+1);
		shutdown(clnt_sock,SHUT_WR);
		close(clnt_sock);
		printf("closed!\n");
		close(clnt_sock);
		return 0;
		
	}
	int len;
		char message[100]="\nPlease send the name of the file including suffix!\n";
		if(write(clnt_sock,message,strlen(message))<0)
			{error_handling("error write:Please send...\n");close(clnt_sock);continue;}
		char filename[100]={0};
		if((len=read(clnt_sock,filename,50))<0)
			{error_handling("error read.\n");close(clnt_sock);continue;}
	if(strcmp(buff,"snd")==0)
	{	
		//pid_t pid;
		//pid=fork();
		//if(pid==0){//child process.
		//printf("PID\n");
		//sleep(100);
		//close(serv_sock);
		time_t timep;
		time(&timep);
		strcat(filename,ctime(&timep));
		int file=open(filename,O_CREAT|O_WRONLY);		
		printf("filename:%s\n",filename);
		if(file==-1)error_handling("open() error!\n");
		while((len=read(clnt_sock,buff,BUF_SIZE))>0)
			write(file,buff,len);
		close(file);//close file
		printf("file received suffessfully!\n");
		close(clnt_sock);
		return 0;
		//}
		//else
			//{close(clnt_sock);continue;}		
	}
	if(strcmp(buff,"get")==0)
	{
		
		//pid_t pid;
		//pid=fork();
		//if(pid==0){//child process.
		//close(serv_sock);
		int file=open(filename,O_RDONLY);		
		printf("filename:%s\n",filename);
		if(file==-1)error_handling("open() error!\n");
		while((len=read(file,buff,BUF_SIZE))>0)
			write(clnt_sock,buff,len);
		shutdown(clnt_sock,SHUT_WR);
		close(file);//close file
		printf("file sended suffessfully!\n");
		close(clnt_sock);
		return 0;
		//}
		//else
			//{close(clnt_sock);continue;}
	}
	else
	{close(clnt_sock);
	return 0;}
	}
	else
	close(clnt_sock);
}//if
	close(serv_sock);
	return 0;
}//while

void error_handling(char *message)
{
	fputs(message, stderr);
	fputc('\n', stderr);
}
void childproc(int sig)
{
	pid_t pid;
	int status;
	pid=waitpid(-1,&status,WNOHANG);
	printf("removed proc id: %d \n",pid);

}






你可能感兴趣的:(并发,linux,通信,网络编程)