基于sqlite3的词典功能

词典功能介绍

实现了客户端通过TCP链接服务器端,然后进行查询单词的功能,服务器端将用户信息和用户查询的历史记录存到数据库中,服务器端词典利用文件IO对词典文件进行查询并将结果发送到客户端。

创建一个sqlite3的数据库

创建 diction.db

linux-zs@ubuntu:~/1024/sqlite3_dictionary/test$ sqlite3 diction.db 
SQLite version 3.8.2 2013-12-06 14:53:30
Enter ".help" for instructions
Enter SQL statements terminated with a ";"

在 diction.db 中添加user和history

两个表用来存放用户信息和查询记录

CREATE TABLE history(name char primary key,word char);
CREATE TABLE user(name char primary key,password char);

客户端代码

#include <sys/types.h>          /* See NOTES */
#include <sys/socket.h>
#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
#include <string.h>

#include <netinet/in.h>
#include <netinet/ip.h> 
#define R 1
#define L 2
#define Q 3
#define H 4

typedef struct{

	int type;
	char name[64];
	char data[256];

}MSG;

int do_reister(int serverfd,MSG *msg);
int do_login(int serverfd,MSG *msg);
int do_function(int serverfd,MSG *msg);
int do_query(int serverfd,MSG *msg);
int do_history(int serverfd,MSG *msg);			  	   

int main(int argc,char *argv[]){

	if(argc != 3){

		printf("%s need input ip&port",argv[0]);
		return -1;

	}

	int serverfd,clientfd;
	pid_t pid;
	MSG msg;
	int choose;
	msg.type = R;
	strcpy(msg.name,"abc");
	strcpy(msg.data,"123");

	serverfd = socket(AF_INET,SOCK_STREAM,0);
	if(serverfd == -1){

		perror("socket is failed");
		return -1;

	}

	struct sockaddr_in server_addr;
	bzero(&server_addr,sizeof(server_addr));
	server_addr.sin_family = AF_INET;
	server_addr.sin_port = htons(atoi(argv[2]));
	server_addr.sin_addr.s_addr = inet_addr(argv[1]);
	socklen_t socklen = sizeof(server_addr);

	if((clientfd = connect(serverfd,(struct sockaddr*)&server_addr,sizeof(server_addr))) == -1){

		perror("accept is failed");
		return -1;

	}
	while(1){

		printf("/**********************************************************/\n");
		printf("/********1:register        2:login        3:quit***********/\n");
		printf("/**********************************************************/\n");
		printf("please input choose:");
		scanf("%d",&choose);
		getchar();
		switch(choose){

		case 1:do_reister(serverfd,&msg);
			   break;
		case 2:if(do_login(serverfd,&msg) == 1){

				   do_function(serverfd,&msg);

			   }
			   break;
		case 3:close(serverfd);
			   exit(0);
			   break;
		default :printf("please input 1-3\n");
				 break;

		}

	}

}

int do_reister(int serverfd,MSG *msg){

	msg->type = R;
	printf("please input name:");
	scanf("%s",msg->name);
	getchar();
	printf("please input data:");
	scanf("%s",msg->data);
	getchar();

	if(send(serverfd,msg,sizeof(MSG),0) < 0){

		printf("send is failed\n");

	}

	if(recv(serverfd,msg,sizeof(MSG),0) < 0){

		printf("recv is failed\n");

	}

	printf("%s\n",msg->data);

	return 0;

}

int do_login(int serverfd,MSG *msg){

	msg->type = L;
	printf("please input name:");
	scanf("%s",msg->name);
	getchar();
	printf("please input data:");
	scanf("%s",msg->data);
	getchar();

	if(send(serverfd,msg,sizeof(MSG),0) < 0){

		printf("send is failed\n");

	}

	if(recv(serverfd,msg,sizeof(MSG),0) < 0){

		printf("recv is failed\n");

	}

	printf("%s\n",msg->data);
	if(strncmp(msg->data,"OK",2) == 0){

		return 1;

	}

	return 0;

}

int do_function(int serverfd,MSG *msg){

	int choose;
	while(1){
		printf("/**********************************************************/\n");
		printf("/********1:query        2:history        3:quit***********/\n");
		printf("/**********************************************************/\n");
		printf("please input choose:");
		scanf("%d",&choose);
		getchar();

		switch(choose){

		case 1:do_query(serverfd,msg);
			   break;
		case 2:do_history(serverfd,msg);			  	   
			   break;
		case 3:close(serverfd);
			   return -1;
			   break;
		default :printf("please input 1-3\n");
				 break;
		}

	}

	return 0;

}

int do_query(int serverfd,MSG *msg){

	msg->type = Q;
	printf("input word:");
	scanf("%s",msg->data);
	getchar();

	if(send(serverfd,msg,sizeof(MSG),0) < 0){

		perror("send");
		return -1;

	}

	if(recv(serverfd,msg,sizeof(MSG),0) < 0){

		perror("recv");
		return -1;

	}

	printf("%s\n",msg->data);

	return 0;

}

int do_history(int serverfd,MSG *msg){

	msg->type = H;

	if(send(serverfd,msg,sizeof(MSG),0) < 0){

		perror("send");
		return -1;

	}

	while(1){

	recv(serverfd,msg,sizeof(MSG),0);
		
		if((strncmp(msg->data,"(null)",6) == 0) || (msg->data[0] == '\0')){
		
		break;
		
		}
		printf("%s\n",msg->data);
	}

	

	return 0;

}

服务器端代码

#include <sys/types.h>          /* See NOTES */
#include <sys/socket.h>
#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
#include <string.h>
#include <netinet/in.h>
#include <netinet/ip.h> 
#include <signal.h>
#include <sqlite3.h>
#include <time.h>

#define R 1
#define L 2
#define Q 3
#define H 4

typedef struct{

	int type;
	char name[64];
	char data[256];

}MSG;

int do_client(int clientfd,MSG *msg,sqlite3 *db);
int do_reister(int clientfd,MSG *msg,sqlite3 *db);
int do_login(int clientfd,MSG *msg,sqlite3 *db);
int do_query(int clientfd,MSG *msg,sqlite3 *db);
int do_history(int clientfd,MSG *msg,sqlite3 *db);

int main(int argc,char *argv[]){

	if(argc != 3){

		printf("%s need input ip&port",argv[0]);
		return -1;

	}

	int serverfd,clientfd;
	pid_t pid;
	MSG msg;
	sqlite3 *db;

	if(sqlite3_open("diction.db",&db) != SQLITE_OK){

		printf("open diction.db is failed erro:%s\n",sqlite3_errmsg(db));
		return -1;

	}else{

		printf("open diction.db is success\n");

	}


	serverfd = socket(AF_INET,SOCK_STREAM,0);
	if(serverfd == -1){

		perror("socket is failed");
		return -1;

	}

	struct sockaddr_in server_addr;
	bzero(&server_addr,sizeof(server_addr));
	server_addr.sin_family = AF_INET;
	server_addr.sin_port = htons(atoi(argv[2]));
	server_addr.sin_addr.s_addr = inet_addr(argv[1]);
	socklen_t socklen = sizeof(server_addr);
	if(bind(serverfd,(struct sockaddr *)&server_addr,socklen) == -1){

		perror("bind is failed");
		return -1;

	}

	if(listen(serverfd,8) == -1){

		perror("listen is failed");
		return -1;

	}

	signal(SIGCHLD, SIG_IGN);

	while(1){

		if((clientfd = accept(serverfd,NULL,NULL)) == -1){

			perror("accept is failed");
			return -1;

		}

		pid = fork();
		if(pid < 0){

			perror("fork is failed");
			return -1;

		}else if(pid > 0){

			close(clientfd);

		}else{

			do_client(clientfd,&msg,db);

		}

	}

}



int do_client(int clientfd,MSG *msg,sqlite3 *db){

	while(recv(clientfd,msg,sizeof(MSG),0) > 0){

		switch(msg->type){

		case R:do_reister(clientfd,msg,db);
			   break;
		case L:do_login(clientfd,msg,db);
			   break;
		case Q:do_query(clientfd,msg,db);
			   break;
		case H:do_history(clientfd,msg,db);
			   break;

		}

	}
	printf("client exit.\n");
	close(clientfd);
	exit(0);
}

int do_reister(int clientfd,MSG *msg,sqlite3 *db){

	char *errmsg;
	char sql[128];
	sprintf(sql,"insert into user values('%s','%s')",msg->name,msg->data);

	if(sqlite3_exec(db,sql,NULL,NULL,&errmsg) != SQLITE_OK){

		printf("%s\n",errmsg);
		strcpy(msg->data,"insert is failed");

	}else{

		printf("insert is success\n");
		strcpy(msg->data,"insert is success");

	}

	if(send(clientfd,msg,sizeof(MSG),0) < 0){

		perror("send");

	}

	return 0;

}

int do_login(int clientfd,MSG *msg,sqlite3 *db){

	char **pazresult;
	int pnrow;
	int pncolunm;
	char *errmsg;
	char sql[128];
	sprintf(sql,"select * from user where name='%s' and password='%s';",msg->name,msg->data);

	if(sqlite3_get_table(db,sql,&pazresult,&pnrow,&pncolunm,&errmsg) != SQLITE_OK){

		printf("%s\n",errmsg);
		strcpy(msg->data,"sqlite select  is failed");

	}

	if(pnrow > 0){

		strcpy(msg->data,"OK");

	}else{

		strcpy(msg->data,"don't have the user or password erro");

	}



	if(send(clientfd,msg,sizeof(MSG),0) < 0){

		perror("send");

	}


	return 0;

}
int do_query(int clientfd,MSG *msg,sqlite3 *db){

	char word[64];
	char dic_read[512];
	FILE *fp;
	int len;
	int ret;
	char *p;
	char sql[128];
	char *errmsg;
	time_t t;

	fp = fopen("dict.txt","r");
	if(fp == NULL){

		perror("send");
		strcpy(msg->data,"open dict.txt failed");
		if(send(clientfd,msg,sizeof(MSG),0) < 0){

			perror("send");

		}

		return -1;

	}

	strcpy(word,msg->data);
	len = strlen(word);
	printf("%d\n",len);
	while(fgets(dic_read,512,fp) != NULL){
		//printf("%s\n",dic_read);
		ret = strncmp(word,dic_read,len);
		if(ret > 0){

			continue;

		}
		if(ret < 0 || (ret == 0 && dic_read[len] != ' ')){

			break;

		}

		p = dic_read + len;
		while(*p == ' '){

			p++;

		}


		strcpy(msg->data,p);
		time(&t);
		sprintf(sql,"insert into history values('%s','%s','%s');",msg->name,word,ctime(&t));
		printf("%s\n",sql);
		if(sqlite3_exec(db,sql,NULL,NULL,&errmsg) != SQLITE_OK){

			printf("%s\n",errmsg);
			sprintf(msg->data,"%s:%s \n but query history no input sql",word,p);
			send(clientfd,msg,sizeof(MSG),0);
			return 0;

		}
		send(clientfd,msg,sizeof(MSG),0);

		fclose(fp);
		return 0;

	}

	strcpy(msg->data,"no find the word");
	send(clientfd,msg,sizeof(MSG),0);
	fclose(fp);
	return 0;

}
int do_history(int clientfd,MSG *msg,sqlite3 *db){

	char **pazresult;
	int pnrow;
	int pncolunm;
	char *errmsg;
	char sql[128];
	int i,j,k;

	sprintf(sql,"select word,time from history where name = '%s';",msg->name);
	if(sqlite3_get_table(db,sql,&pazresult,&pnrow,&pncolunm,&errmsg) != SQLITE_OK){

		printf("%s\n",errmsg);
		return -1;

	}
	i = j = 0;
	k = pncolunm;
	printf("pnrow:%d,pncolunm:%d\n",pnrow,pncolunm);
	for(i;i< pnrow;i++){

		for(j;j< pncolunm;j++){


		}
		sprintf(msg->data,"%s:%s\n",pazresult[k],pazresult[k+1]);

		if(send(clientfd,msg,sizeof(MSG),0) < 0){

			perror("send");

		}
		k = k + pncolunm;

	}

	strcpy(msg->data,"(null)");
	send(clientfd,msg,sizeof(MSG),0);
	printf("abc\n");

	return 0;

}

词典文件

词典为““dict.txt”,以下是文件部分内容;

a                indef art one
abacus           n.frame with beads that slide along parallel rods, used for teaching numbers to children, and (in some countries) for counting
abandon          v.  go away from (a person or thing or place) not intending to return; forsake; desert
abandonment      n.  abandoning
abase            v. ~ oneself/sb lower oneself/sb in dignity; degrade oneself/sb ;
abash            to destroy the self-possession or self-confidence of:disconcert
abashed          adj. ~ embarrassed; ashamed
abate            v. make or become less
abattoir         n. = slaughterhouse (slaughter)
abbess           n. woman who is head of a convent or nunnery
abbey            n.  buildingin which monks or nuns live as a community under an abbot or abbess
abbot            n. man who is head of a monastery or abbey
abbreviate       v. ~ sth shorten (a word, phrase, etc), esp by omitting letters
abbreviation     n.  abbreviating or being abbreviated
abdicate         v.  resign from or formally renounce the throne
abdication       giving up control, authority
abdomen          n.  part of the body below the chest and diaphragm, containing the stomach, bowels and digestive organs
abdominal        adj. in, of or for the abdomen
abduct           v. take away illegally, using force or deception; kidnap ;
abduction        A carrying away of a person against his will, or illegally.
abed             In bed; on a bed.
aberrant         adj. not following the normal or correct way
aberration       n.  deviation from what is accepted as normal or right
abet             v.  ~ sb (in sth) help or encourage sb to commit an offence or do sth wrong
abeyance         n. be in abeyance; fall/go into abeyance (of a right, rule, problem, etc) be suspended temporarily; not be in force or use for a time
abhor            v. feel hatred and disgust for (sb/sth); detest
abhorrence       n. hatred and disgust
abhorrent        adj. ~ disgusting; hateful
abidance         An abiding.
abide            v.  (esp with can/could, in negative sentences or questions can/could) tolerate (sb/sth); endure; bear
abiding          adj. enduring; permanent
ability          n.  capacity or power to do sth physical or mental
abject           adj.  wretched; hopeless
abjure           v. promise or swear to give up (a claim, an opinion, a belief, etc); renounce formally
ablaze           adj.  burning; on fire
able             adj. be ~ to do sth have the power, means or opportunity to do sth
able-bodied      adj. healthy, fit and strong
ablution         n. (fml or joc ) ceremonial washing of the body, hands, sacred vessels, etc
ably             adv. in an able manner
abnegate         vt. to give up (rights or a claim, for example); renounce.
abnegation       n.  denial or renunciation (of a doctrine)
abnormal         adj. different, esp in an undesirable way, from what is normal, ordinary or expected
abnormally       adv: abnormally large feet
aboard           adv. part, prep on or into a ship, an aircraft, a train or a bus ,
abode            n.  house; home
abolish          v. end the existence of
abolition        n. abolishing or being abolished
abolitionism     principles or measures fostering abolition especially of slavery
abolitionist     n. person who favours abolition, esp of capital punishment
abominable       adj.  ~(fml ) causing disgust; detestable
abominate        v. feel hatred or disgust for (sth/sb); detest; loathe
abomination      n.  feeling of disgust and extreme hatred
aboriginal       adj. inhabiting a land from a very early period, esp before the arrival of colonists
aborigine        n. aboriginal inhabitant
abortive         adj. coming to nothing; unsuccessful
abound           v.  be very plentiful; exist in great numbers
about            adv.  a little more or less than; a little before or after; approximately .;
above            adv.  at or to a higher point; overhead
aboveboard       be in a straightforward manner
abracadabra      n, interj meaningless word said as a supposedly magic formula esp by conjurors while performing magic tricks
abrade           v. wear away by rubbing; scrape off
abraded          rubbed off/worn away by friction
abrasion         n.  scraping or wearing away; rubbing off ;
abrasive         adj.  that scrapes or rubs sth away; rough
abreast          adv.  ~ side by side (with sb/sth) and facing the same way
abridge          v. make shorter, esp by using fewer words; condense
abridgement      n.  shortening of a book, etc ,
abridgment       a shortened version of a written work
abroad           adv.  in or to a foreign country or countries; away from one's own country
abrogate         v. cancel, repeal or annul (sth)
abrupt           adj.  sudden and unexpected
abruptly         adv.
abscess          n. swollen part of the body in which a thick yellowish liquid has collected
abscission       The act of cutting off, as in a surgical operation.
abscond          v. ~go away suddenly and secretly, esp in order to avoid arrest
absence          n.  ~ being away
absent           adj.  ~ not present (at sth); at another place (than.)
absentee         n. person who is absent
absenteeism      n. frequent absence from school or work, esp without good reason ,
absinth          [ absinthe: ] a potent green alcoholic drink, technically a gin, originally having high wormwood content
absinthe         n. bitter green alcoholic drink made with wormwood and other herbs
absolute         adj.  complete; total
absolutely       adv.  completely
absolution       n. formal declaration by a priest that a person's sins have been forgiven
absolve          v. ~ sb (fml esp law , ) clear sb (of guilt); declare sb free (from blame, a promise, a duty, etc)
absorb           v.  take (sth) in; suck up
absorbed         adj. with one's attention fully held
absorbent        n, adj that is able to take in moisture, etc
absorbing        adj. holding the attention fully
  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值