C语言编写一个简易的网络词典

摘要:电子辞典是指将传统的辞典中的内容转换为数字格式存储的文件,并且将它们保存在存储器中。用户使用时只需要通过键盘输入需要查询的条目,电子辞典通过自身携带的处理器,按照一定的编码查询方式便可以找到相关条目的解释,并在显示屏上显示从而让用户了解。比如输入一个英文单词后便可以找到该单词的中文解释、音标,有的产品还可以进行实际的发声演
示。同样的道理,输入一个中文进行查询也能够查到大致的英文单词。

项目简介:客户端与服务端使用TCP协议进行通信,由客户端向服务端发送请求,服务端解析指令反馈相应信息并执行对应操作,从而实现帐号注册、登录,单词释义,以及历史记录查询等功能。

结构体定义:

typedef struct
{
	char _username[25]; //用户名
	char _password[25]; //密码
}__attribute__((__packed__))user_t;

typedef struct
{
	int type;           //消息类型
	int size;           //消息大小
	union
	{
		user_t uinfo;	    //用户信息
		char   _word[100]; 
	}content;

//客户端填单词,服务端填写单词解释
#define word         content._word
#define username     content.uinfo._username
#define password       content.uinfo._password
}__attribute__((__packed__))mhead_t;

功能描述

1.服务端使用多进程技术,实现并发处理多个客户端请求

2.服务器接收客户端的注册请求,将用户名和密码加入到用户注册表中,并创建相应的查询记录

3.服务器接收客户端登录请求,将在SQLite3数据库中查询相关用户名, 并比对密码,反馈比对结果

4.客户端登录成功后,开启单词释义和历史查询功能

5.服务器接收到释义查询请求后,在数据库中搜索单词并返回释义

6.服务器接收到历史查询请求后,返回该用户查询记录表中的相关数据

完整代码:

头文件

#ifndef _HEAD_H_
#define _HEAD_H_
 #include 
  #include 
       #include 

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

//消息的类型
#define USER_REGISTER    10
#define USER_LOGIN       20
#define USER_WORD        30
#define USER_SUCCESS     40
#define USER_FAILURE     50

//__attribute__((__packed__))
//作用:告诉编译器在编译的过程中取消优化对齐。
//      方便我们在发送和接收数据的时候一个字节一个字节的排列 
typedef struct
{
	char _username[25]; //用户名
	char _password[25]; //密码
}__attribute__((__packed__))user_t;

typedef struct
{
	int type;           //消息类型
	int size;           //消息大小
	union
	{
		user_t uinfo;	    //用户信息
		char   _word[100]; 
	}content;

//客户端填单词,服务端填写单词解释
#define word         content._word
#define username     content.uinfo._username
#define password       content.uinfo._password
}__attribute__((__packed__))mhead_t;

//'\'表示多行链接上一行表示, #deifne ....do...while(0);
//表示封装成独立的语法单元,防止被语法错误。
//注意:'\'之后不要留空格,要不然编译会有警告

#define EXEC_SQL(db,sql,errmsg) do{\
	if(sqlite3_exec(db,sql,NULL,NULL,&errmsg) < 0)\
	{\
		fprintf(stderr,"sqlite3 execl [%s] error : %s.\n",sql,errmsg);\
		exit(EXIT_FAILURE);\
	}\
}while(0);

#endif

服务器功能

#include "head.h" 

int do_register(int sockfd,sqlite3 *pdb,char *_username,char *_password)
{
	char *errmsg;
	char buf[1024];
	char **dbresult;
	int nrow = 0,ncolumn = 0;
	char sql[1024] = {0};
	mhead_t *head = (mhead_t *)buf;	

	sprintf(sql,"select * from user_table where NAME='%s';",_username);
	if(sqlite3_get_table(pdb,sql,&dbresult,&nrow,&ncolumn,&errmsg) != 0)
	{
		fprintf(stderr,"sqlite3 get table error : %s.\n",errmsg);
		exit(EXIT_FAILURE);
	}

	//没有这样的用户名
	if(nrow == 0)
	{
		//录入数据库
		bzero(sql,sizeof(sql));
		sprintf(sql,"insert into user_table values('%s','%s');",_username,_password);
		EXEC_SQL(pdb,sql,errmsg);
		
		printf("ok ........\n");

		head->type = USER_SUCCESS;
		if(send(sockfd,buf,sizeof(mhead_t),0) < 0)
		{
			perror("Fail to send");
			exit(EXIT_FAILURE);
		}
	//注册失败,用户名存在
	}else{
		head->type = USER_FAILURE;
		if(send(sockfd,buf,sizeof(mhead_t),0) < 0)
		{
			perror("Fail to send");
			exit(EXIT_FAILURE);
		}
		//表示未知	
		printf("???????\n");
	}
	//插入到数据库之后,释放dbresult结果
	sqlite3_free_table(dbresult);
	return 0;
}
//登录
int denglu(int sockfd,sqlite3 *pdb,char *_username,char *_password)
{
	char *errmsg;
	char buf[1024];
	char **dbresult;
	int nrow = 0,ncolumn = 0;
	char sql[1024] = {0};
	mhead_t *head = (mhead_t *)buf;	

	bzero(sql,sizeof(sql));
	sprintf(sql,"select *from user_table where NAME='%s';",_username);
		if(sqlite3_get_table(pdb,sql,&dbresult,&nrow,&ncolumn,&errmsg) != 0)
	{
		fprintf(stderr,"sqlite3 get table error : %s.\n",errmsg);
		exit(EXIT_FAILURE);
	}
		else{
		if(nrow==1)
		{
		printf("denglu success\n");
		memset(buf,0,sizeof(buf));
		head->type = USER_SUCCESS;
				if(send(sockfd,buf,sizeof(mhead_t),0) < 0)
		{
			perror("Fail to send");
			exit(EXIT_FAILURE);
		}

		}
		else{

	head->type = USER_FAILURE;

			printf("denglu fail\n");
	if(send(sockfd,buf,sizeof(mhead_t),0) < 0)
		{
			perror("Fail to send");
			exit(EXIT_FAILURE);
		}

		}
		}
}
//查找单词
int chaword(int sockfd,sqlite3 *pdb,char *cword)
{

	char *errmsg;
	char buf[1024];
	char **dbresult;
	int nrow = 0,ncolumn = 0,index=0;
	char sql[1024] = {0};
	mhead_t *head = (mhead_t *)buf;
	printf("%s",cword);
	bzero(sql,sizeof(sql));

	sprintf(sql,"select * from dict_table where word='%s';",cword);
	if(sqlite3_get_table(pdb,sql,&dbresult,&nrow,&ncolumn,&errmsg) != 0)
	{
		fprintf(stderr,"sqlite3 get table error : %s.\n",errmsg);
		exit(EXIT_FAILURE);
	}
else{
	if(nrow==0)//
	{
		printf("norw=0\n");
		head->type=USER_FAILURE;
		if(send(sockfd,buf,sizeof(mhead_t),0)<0)
		{
			perror("Fail to send");
			exit(EXIT_FAILURE);
		}

	}
	else{
	head->type=USER_SUCCESS;
	for(int i=0;i<=nrow;i++)
	{
		for(int j=0;jword,dbresult[index+1]);
		if(send(sockfd,buf,sizeof(mhead_t),0)<0)
		{
			perror("Fail to send");
			exit(EXIT_FAILURE);
		}

				i=nrow+1;
				break;
			}
			index++;
		}
	}
	}
}
	sqlite3_free_table(dbresult);
}

int do_client(int sockfd,sqlite3 *pdb)
{
	int n;
	long count = 0;
	char buf[1024];
	mhead_t *head = (mhead_t *)buf;	

	while(1)
	{
		count = 0;
		//接收协议头
		while(1)
		{
			n = recv(sockfd,buf + count,sizeof(mhead_t) - count,0);
			
			if(n <= 0){
				exit(EXIT_FAILURE);
			}


			count += n;
			printf("count : %ld mhead_t : %ld\n",count,sizeof(mhead_t));
			if(count == sizeof(mhead_t))
				break;
		}

		switch(head->type)
		{
		case USER_REGISTER:
			do_register(sockfd,pdb,head->username,head->password);	
			break;
		
		case USER_LOGIN:
			denglu(sockfd,pdb,head->username,head->password);	
			break;
		case USER_WORD:
			chaword(sockfd,pdb,head->word);
			break;
		defalut:
			exit(EXIT_SUCCESS);
		}	
	}

	return 0;
}

服务器主程序

#include "head.h"
void signal_handler(int signum)
{
	waitpid(-1,NULL,WNOHANG);
	return;
}
int init_tcp(char *ip,char *port)
{
	int sockfd;
	struct sockaddr_in server_addr;
	
	if((sockfd = socket(AF_INET,SOCK_STREAM,0)) < 0)
	{
		perror("Fail to socket");
		exit(EXIT_FAILURE);
	}
	bzero(&server_addr,sizeof(server_addr));
	server_addr.sin_family = AF_INET;
	server_addr.sin_port   = htons(atoi(port));
	server_addr.sin_addr.s_addr = inet_addr(ip);

	if(bind(sockfd,(struct sockaddr *)&server_addr,sizeof(server_addr)) < 0)
	{
		perror("Fail to bind");
		exit(EXIT_FAILURE);
	}
	
	listen(sockfd,5);
	printf("listen....\n");
	return sockfd;
}

//.server ip port db
//数据库中已经手动创建了2个表:user_table,word_table
//注:由于我们后面函数要传承,故这里的const应该去掉
int main(int argc, char *argv[])
{
	int pid;	
	sqlite3 *pdb;
	char *errmsg;
	char *sql="craete table if not exists system(NAME text,password text)";
int ret;
	int listenfd,connect_fd;
	int addr_len = sizeof(struct sockaddr);
	struct sockaddr_in peer_addr;
	
	if(argc < 4)
	{
		fprintf(stderr,"Usage : %s ip port system.db.\n",argv[0]);
		exit(EXIT_FAILURE);
	}

	//探测子进程的改变状态,回收僵尸态子进程
	if(signal(SIGCHLD,signal_handler) == SIG_ERR)
	{
		perror("Fail to signal");
		exit(EXIT_FAILURE);
	}

	if(sqlite3_open(argv[3],&pdb) != SQLITE_OK)
	{
		fprintf(stderr,"sqlite3 open %s : %s.\n",argv[3],sqlite3_errmsg(pdb));
		exit(EXIT_FAILURE);
	}

	//初始化tcp连`接,得到监听套接字
	listenfd = init_tcp(argv[1],argv[2]);

	//提取客户段的链接请求,创建子进程和客户端交互
	while(1)
	{
		if((connect_fd = accept(listenfd,(struct sockaddr *)&peer_addr,&addr_len)) < 0)
		{
			perror("Fail to accept");
			exit(EXIT_FAILURE);
		}
		
		if((pid = fork()) < 0)
		{
			perror("Fail to fork");
			exit(EXIT_FAILURE);
		}

		//创建子进程处理客户端的请求
		if(pid == 0){
			close(listenfd);
			do_client(connect_fd,pdb);
		}

		close(connect_fd);
	}
	sqlite3_close(pdb);
	exit(EXIT_SUCCESS);
}

客户端

#include "head.h"
//用户提示界面1
void help_info1()
{
	printf("\t-----------------------------------------------\n");
	printf("\t|               HENRY   在线辞典               |\n");
	printf("\t|版本:0.0.1                                    |\n");
	printf("\t|作者:土拨鼠℡                                  |\n");
	printf("\t|功能:                                         |\n");
	printf("\t|    [1] 登录                                  |\n");
	printf("\t|    [2] 注册                                  |\n");
	printf("\t|    [3] 退出                                  |\n");
	printf("\t|注意:用户只有登录成功后才能进入查单词界面     |\n");
	printf("\t------------------------------------------------\n");
	return;
}
void find_info()
{
		printf("\t-----------------------------------------------\n");
		printf("\t|     欢迎进入单词查询系统,很高兴为您服务        |\n");
		printf("\t|版本:0.0.1                                    |\n");
		printf("\t|作者:土拨鼠℡                                  |\n");
		printf("\t|功能:                                         |\n");
		printf("\t|    [1] 查单词                                |\n");
		printf("\t|    [2] 查询历史记录                          |\n");
		printf("\t|    [3] 退出查询系统                          |\n");
		printf("\t|注意:用户只有登录成功后才能进入查单词界面     |\n");
		printf("\t------------------------------------------------\n");
		return;
}

//用户输入指令,供大家选择
enum{
	LOGIN    = 1,  //登陆
	REGISTER = 2,  //注册
	QUIT     = 3,  //退出
	QUERY    = 1,  //查询单词
	HISTORY  = 2,  //查询历史
};
int denglu(int sockfd)
{
		int n = 0;
		int count = 0;
		char buf[1024] = {0};
		//定义发送的协议头
		mhead_t *head = (mhead_t *)buf;
	
		printf("\n您正在登录,请输入用户名和密码\n");
	
		head->type = USER_LOGIN;
		head->size = sizeof(mhead_t);
	
		printf("Input username : ");
		fgets(head->username,sizeof(head->username),stdin);
		head->username[strlen(head->username) - 1] = '\0';
	
		printf("Input password : ");
		fgets(head->password,sizeof(head->password),stdin);
		head->password[strlen(head->password) - 1] = '\0';
	
		//发给服务器端
		
		if(send(sockfd,buf,sizeof(mhead_t),0) < 0)
		{
			perror("Fail to send");
			exit(EXIT_FAILURE);
		}
		
		bzero(&buf,sizeof(buf));
		while(1)
		{
			//接收数据,TCP是可靠的连接,若是数据
			//未完全接收的话,可以在接收
			n = recv(sockfd,buf + count,sizeof(mhead_t) - count,0);
	
			if(n <= 0){
				perror("Fail to send");
				exit(EXIT_FAILURE);
			}
			//若是数据未发送完成,再次接收的时候可补充
			count += n;
			if(count == sizeof(mhead_t))
				break;
		}
	
		if(head->type == USER_SUCCESS)
		{
			printf("\n恭喜您,登录成功!\n");	
			return 0;
		}else{
			printf("\n密码或用户名输入不正确\n");	
			return -1;
		}
}


int init_tcp(char *ip,char *port)
{
	int sockfd;
	struct sockaddr_in server_addr;

	if((sockfd = socket(AF_INET,SOCK_STREAM,0)) < 0)
	{
		perror("Fail to socket");	
		exit(EXIT_FAILURE);
	}

	bzero(&server_addr,sizeof(server_addr));
	server_addr.sin_family = AF_INET;
	server_addr.sin_port = htons(atoi(port));
	server_addr.sin_addr.s_addr = inet_addr(ip);

	if(connect(sockfd,(struct sockaddr *)&server_addr,sizeof(server_addr)) < 0)
	{
		perror("Fail to bind");	
		exit(EXIT_FAILURE);
	}

	return sockfd;
}

int do_register(int sockfd)
{
	int n = 0;
	int count = 0;
	char buf[1024] = {0};
	//定义发送的协议头
	mhead_t *head = (mhead_t *)buf;

	printf("\n您正在注册,请输入用户名和密码\n");

	head->type = USER_REGISTER;
	head->size = sizeof(mhead_t);

	printf("Input username : ");
	fgets(head->username,sizeof(head->username),stdin);
	head->username[strlen(head->username) - 1] = '\0';

	printf("Input password : ");
	fgets(head->password,sizeof(head->password),stdin);
	head->password[strlen(head->password) - 1] = '\0';

	//发给服务器端
	
	if(send(sockfd,buf,sizeof(mhead_t),0) < 0)
	{
		perror("Fail1 to send");
		exit(EXIT_FAILURE);
	}
	
	bzero(&buf,sizeof(buf));
	while(1)
	{
		//接收数据,TCP是可靠的连接,若是数据
		//未完全接收的话,可以在接收
		n = recv(sockfd,buf + count,sizeof(mhead_t) - count,0);

		if(n <= 0){
			perror("Fail2 to send");
			exit(EXIT_FAILURE);
		}
		//若是数据未发送完成,再次接收的时候可补充
		count += n;
		if(count == sizeof(mhead_t))
			break;
	}

	if(head->type == USER_SUCCESS)
	{
		printf("\n恭喜您,注册成功!\n");	
		return 0;
	}else{
		printf("\n很遗憾,这个用户名已经被其它用户注册过了,请重新注册");	
		return -1;
	}

}
int chaword(int sockfd)
{
	time_t t;
	FILE *fp;
	char buf[1024] = {0};
	int count=0,n=0;	
	char gword[100]={0};
	mhead_t *head = (mhead_t *)buf;
	head->type=USER_WORD;
	head->size = sizeof(mhead_t);
	printf("请输入要查询的单词\n");
	fgets(head->word,sizeof(head->word),stdin);
	head->username[strlen(head->username) - 1] = '\0';
	strcpy(gword,head->word);

	if(send(sockfd,buf,sizeof(mhead_t),0) < 0)
	{
		perror("Fail1 to send");
		exit(EXIT_FAILURE);
	}
	//memset(buf,0,sizeof(buf));
	bzero(&buf,sizeof(buf));
		while(1)
	{
		//接收数据,TCP是可靠的连接,若是数据
		//未完全接收的话,可以在接收
		n = recv(sockfd,buf + count,sizeof(mhead_t) - count,0);

		if(n <= 0){
			perror("Fail2 to recv");
			exit(EXIT_FAILURE);
		}
		//若是数据未发送完成,再次接收的时候可补充
		count += n;
		if(count == sizeof(mhead_t))
		{
			break;
		}
	}
		if(head->type==USER_SUCCESS)
		{
		
			printf("%s\n",head->word);

		fp=fopen("log.txt","a+");
		fprintf(fp,"%s\n%s\n%s\n",ctime(&t),gword,head->word);
		fclose(fp);
		}

else
{ 
 printf("没有这个单词\n");
}		
}

int history_word(int sockfd)
{
	int ch;
	FILE *fp;
	time_t t;
	fp=fopen("log.txt","r");
	printf("当前时间: %s",ctime(&t));
	while(1)
	{
		ch=fgetc(fp);
		if(ch==EOF)
			break;
		fputc(ch,stdout);
	}
	fclose(fp);
	return 0;

}

int chaxun(int sockfd)
{
	int cmd;
	while(1)
	{
	find_info();
	printf("\n\n请选择>");
	scanf("%d",&cmd);
	getchar();
	switch(cmd)
	{
	case QUERY:
			 chaword(sockfd);
			continue;
	case HISTORY:
			history_word(sockfd);
			continue;
	case QUIT:
			exit(EXIT_SUCCESS);
	default:
			printf("Unknow cmd.\n");
			continue;
	}
	}	
}

int do_task(int sockfd)
{
	int cmd;
	while(1)
	{
		//提示界面帮助,用户选择
		help_info1();	

		printf("\n\n请选择>");
		scanf("%d",&cmd);
		//吃掉回车键
		getchar();
		switch(cmd)
		{
			//用户注册,我们先来写注册的函数
			case REGISTER:
				if(do_register(sockfd) < 0)
				{break;}
				else{
					continue;}
					
			//用户登陆
			case LOGIN:	
					if(denglu(sockfd)<0)
					{break;}
					 else{chaxun(sockfd);}
			case QUIT:
				exit(EXIT_SUCCESS);
			default:
				printf("Unknow cmd.\n");
				continue;
		}
	}
	return 0;
}

//./client ip port 
//由于后面要传递参数,故这里的const省略
int main(int argc, char *argv[])
{
	int sockfd;	
	int addr_len = sizeof(struct sockaddr);
	struct sockaddr_in peer_addr;

	if(argc < 3)
	{
		fprintf(stderr,"Usage : %s argv[1] argv[2]\n",argv[0]);	
		exit(EXIT_FAILURE);
	}

	sockfd = init_tcp(argv[1],argv[2]);

	do_task(sockfd);

	return 0;
}

你可能感兴趣的:(服务器,运维)