词典功能介绍

实现了客户端通过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 4typedef 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 4typedef 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

基于sqlite3的词典功能相关推荐

  1. 【Qt编程】基于Qt的词典开发系列六--界面美化设计

    本文讲一讲界面设计,作品要面向用户,界面设计的好坏直接影响到用户的体验.现在的窗口设计基本都是扁平化的,你可以从window XP与window 8的窗口可以明显感觉出来.当然除了窗口本身的效果,窗口 ...

  2. 【Qt编程】基于Qt的词典开发系列十二调用讲述人

    我们知道,win7系统自带有讲述人,即可以机器读出当前内容,具体可以将电脑锁定,然后点击左下角的按钮即可.之前在用Matlab写扫雷游戏的时候,也曾经调用过讲述人来进行游戏的语音提示.具体的Matla ...

  3. 【Qt编程】基于Qt的词典开发系列一--词典框架设计及成品展示

    去年暑假的时候,作为学习Qt的实战,我写了一个名为<我爱查词典>的词典软件.后来由于导师项目及上课等原因,时间不足,所以该软件的部分功能欠缺,性能有待改善.这学期重新拿出来看时,又有很多东 ...

  4. think php ajax分页,thinkPHP5框架实现基于ajax的分页功能示例

    本文实例讲述了thinkPHP5框架实现基于ajax的分页功能.分享给大家供大家参考,具体如下: 最近一个页面的选项卡又牵扯到ajax分页,所以研究了一下tp5的ajax分页使用方法 首先看一下tp5 ...

  5. 基于nginx实现缓存功能及uptream模块详细使用方法

    基于nginx实现缓存功能及uptream模块详细使用方法 一般情况下,前端使用nginx做代理或7层负载并向后实现varish/squid做cache server的效果要好的多 nginx与squ ...

  6. 基于AVR单片机PWM功能的数控恒流源研制

    随着电子技术的深入发展,各种智能仪器越来越多,涉及领域越来越广,而仪器对电源的要求也越来越高.现今,电源设备有朝着数字化方向发展的趋势.然而绝大多数数控电源设计是通过高位数的A/D和D/A芯片来实现的 ...

  7. 基于STM32的多功能门禁系统(AS608指纹识别、密码解锁、刷卡解锁)

    目录 一.项目功能 二.视频 三.原理图 4.材料选择 5.部分程序 资料下载地址:基于STM32的多功能门禁系统 一.项目功能 1.AS608指纹解锁:可以录入.删除.验证指纹: 2.密码解锁:可以 ...

  8. 【图像处理】基于matlab GUI多功能图像处理系统【含Matlab源码 1876期】

    ⛄一.获取代码方式 获取代码方式1: 完整代码已上传我的资源:[图像处理]基于matlab GUI多功能图像处理系统[含Matlab源码 1876期] 点击上面蓝色字体,直接付费下载,即可. 获取代码 ...

  9. 基于canvas剪辑区域功能实现橡皮擦效果

    这篇文章主要介绍了基于canvas剪辑区域功能实现橡皮擦效果,非常不错,具有参考借鉴价值,需要的朋友可以参考下 这是基础结构 没什么好说的 ?<!DOCTYPE html> <htm ...

最新文章

  1. cpu密集型 计算密集型 io密集型 简介
  2. MySQL【环境搭建 01】Linux root 用户部署 mysql-5.7.28 及 not allowed to connect to this MySQL server 和中文乱码问题处理
  3. TP5的目录常量和路径
  4. SAP Spartacus organization unit list的实现Component
  5. mysql(slow-query) 快速开启慢日志查询的方法
  6. 存储类、作用域、生命周期、链接属性
  7. 报告显示,媒体行业已成撞库攻击常见目标
  8. git 命令 clone分支的代码
  9. 华为云PB级数据库GaussDB(for Redis)揭秘第六期:Feed流场景中的应用
  10. HUE与HDFS的集成
  11. 计算机显卡驱动不匹配,显卡驱动与系统不兼容?尤其是老电脑
  12. 马尔可夫链预测模型的应用——以安徽各城市人均GDP预测为例
  13. IDrawingDoc Interface 学习笔记
  14. Git提交前端代码遇到Lint errors found in the listed files.和husky - pre-push hook failed (add --no-verify)
  15. 国开大学 C语言程序 形考任务4,[国家开放大学] 国开电大人体生理学形考任务4...
  16. 开源摄影测量与遥感处理软件OSSIM简介
  17. iOS音乐播放器小技巧
  18. 低代码编程核心技术概念
  19. nimi SearchEngin 项目思路及算法
  20. 2019 ICPC Asia Nanchang Regional

热门文章

  1. c语言 指针函数pdf,c语言函数,指针与数组.pdf
  2. Q:如何打开.pkl文件?
  3. Luogu P4299 首都 LCT
  4. Java使用poi操作Excel单元格
  5. java中的特殊文件、日志技术、多线程入门
  6. 【任务平台源码】码帮/辅助注册/雏菊任务/微信辅助系统/任务平台
  7. 深度分析劳保鞋LA认证和CE认证有什么区别
  8. 三种万用遥控器的比较分析
  9. MFC中CString.Format的详细用法和进制转换
  10. php updatexml,php操作XML增删查改