任务要求:
//1.登录注册功能,不能重复登录,重复注册--数据库对比用户信息,成功则登录;失败询问是否注册登录,将注册用户信息存储在数据库(用户信息,历史记录)
//2. 单词查询功能--记录当前用户
//3. 历史记录功能,存储单词,意思,以及查询时间
//4. 基于TCP,支持多客户端连接
//5. 采用数据库保存用户信息与历史记录
//6. 将dict.txt的数据导入到数据库中保存。
//7. 按下ctrl+c退出客户端后,注销该客户端的登录信息
现象展示
将dict.txt的数据导入到数据库中保存
#include <stdio.h>
#include <sqlite3.h>
#include <string.h>
int main(int argc, const char *argv[])
{
//打开数据库
sqlite3* db = NULL;
if(sqlite3_open("./my.db", &db) != SQLITE_OK)
{
fprintf(stderr, "__%d__ sqlite3_open:%s\n", __LINE__, sqlite3_errmsg(db));
return -1;
}
char sql[400] = "create table if not exists dict (word char, mean char)";
char* errmsg = NULL;
//创建表格
if(sqlite3_exec(db, sql, NULL, NULL, &errmsg) != SQLITE_OK)
{
fprintf(stderr, "__%d__ sqlite3_exec:%s\n", __LINE__,errmsg);
return -1;
}
//打开文件
FILE* fp = fopen("./dict.txt", "r");
if(NULL == fp)
{
perror("fopen");
return -1;
}
//循环读取一行,直到读取完毕为止
char buf[300] = "";
char word[50]="", mean[300]="";
int i = 0;
while(fgets(buf, sizeof(buf), fp) != NULL)
{
buf[strlen(buf)-1] = 0;
//分离单词和意思
for(i=0; i<strlen(buf)-2; i++)
{
if(buf[i]!=' ' && buf[i+1]==' ' && buf[i+2]==' ')
{
strncpy(word, buf, i+1);
}
else if(buf[i]==' '&& buf[i+1]==' ' && buf[i+2]!=' ')
{
strcpy(mean, (buf+i+2));
break;
}
}
//插入到数据库中
sprintf(sql, "insert into dict values(\"%s\", \"%s\");", word, mean);
if(sqlite3_exec(db, sql, NULL, NULL, &errmsg) != SQLITE_OK)
{
fprintf(stderr, "__%d__ sqlite3_exec:%s\n", __LINE__,errmsg);
return -1;
}
bzero(word, sizeof(word));
bzero(mean, sizeof(mean));
}
//关闭文件
//关闭数据库
return 0;
}
客户端:
#include <stdio.h>
#include <sqlite3.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <unistd.h>
#include<string.h>
#include<errno.h>
#define err(msg) do{printf("__%d__",__LINE__);perror(msg);return -1;}while(0)
#define PORT 8888
#define IP "192.168.3.92"//127.0.0.1
typedef struct
{
char flag;
char name[20];
char text[128];//密码或单词
}msg;
int do_register(msg *usr,int sfd)
{
printf("正在注册...\n");
ssize_t res;
usr->flag='R';
printf("请输入用户名:");
scanf("%s",usr->name);
printf("请输入密码:");
scanf("%s",usr->text);
if(send(sfd,usr,sizeof(msg),0)<0)err("send");
res = recv(sfd,usr, sizeof(msg), 0);
if(res < 0)err("recv");
else if(0 == res)
{
printf("server is off-line\n");
}
printf("%s\n",usr->text);
return 0;
}
int do_login(msg *usr,int sfd)
{
printf("正在登录...\n");
ssize_t res;
usr->flag='L'; //flag 乱码
printf("请输入用户名:");
scanf("%s",usr->name);
printf("请输入密码:");
scanf("%s",usr->text);
//发送结构体消息包到服务器--服务器比较 用户信息数据库
if(send(sfd,usr,sizeof(msg),0)<0)err("send");
res = recv(sfd,usr,sizeof(msg),0);
if(res < 0)err("recv");
if(strncmp(usr->text,"ok",3)==0)
{
printf("%s : log_in successfully\n",usr->name);
return 1;//登录成功
}
else{
printf("%s\n",usr->text);
}
return 0;
}
int do_search(msg *usr,int sfd)
{
printf("正在查询单词...(#退出)\n");
ssize_t res;
usr->flag='S';
while(1)
{
printf("请输入需要查询的单词:");
scanf("%s",usr->text);
if(strcmp(usr->text,"#")==0)break;
//发送-比较单词库
if(send(sfd,usr,sizeof(msg),0)<0)err("send");
// printf("%c\t%s\t%s\n",usr->flag,usr->name,usr->text);
res=recv(sfd,usr, sizeof(msg), 0);
if(res<0)err("recv");
//打印单词解释
printf("mean:%s\n",usr->text);
}
}
int do_history(msg *usr,int sfd)
{
usr->flag='H';
ssize_t res;
if(send(sfd,usr,sizeof(msg),0)<0)err("send");
printf("the following is history:\n");
//接收查询历史
while(1)
{
res = recv(sfd,usr, sizeof(msg), 0);
if(res<0)err("recv");
else if(res>0)
{
printf("%s\n",usr->text);
}
else
{
printf("this is all history\n");
break;
}
}
return 0;
}
int main(int argc, const char *argv[])
{
//TCP_select模型
//创建套接字
int sfd=socket(AF_INET,SOCK_STREAM,0);
if(sfd<0)err("msg");
//端口快速复用
int reuse = 1;
if(setsockopt(sfd, SOL_SOCKET, SO_REUSEADDR, &reuse, sizeof(reuse)) < 0)err("setsockopt");
//服务器用户地址信息
struct sockaddr_in sin;
sin.sin_family=AF_INET;
sin.sin_port=htons(PORT);
sin.sin_addr.s_addr=inet_addr(IP);//<<inet_addr
//链接
if(connect(sfd,(struct sockaddr*)&sin,sizeof(sin))<0)err("connect");
msg usr;
char choose = 0;
int choice=0;//不初始化
while(1)
{
memset(&usr,0,sizeof(msg));
system("clear");
printf("\t|---------------------------|\n");
printf("\t|--------1. 注册------------|\n");
printf("\t|--------2. 登录------------|\n");
printf("\t|--------3. 退出------------|\n");
printf("\t|---------------------------|\n");
printf("请输入选项>>>");
scanf("%c",&choose);
switch(choose)
{
case '1':
do_register(&usr,sfd);
break;
case '2':
if(do_login(&usr,sfd)>0)
{
goto log_in;//do_login();//登录
}
break;
case '3':
close(sfd);
exit(0);
break;
default:
printf("输入错误,请重新输入\n");
}
printf("输入任意字符清屏>>>\n");
while(getchar()!=10);
}
log_in:
while(1)
{
printf("\t|---------------------------|\n");
printf("\t|--------1. 查询单词--------|\n");
printf("\t|--------2. 历史记录--------|\n");
printf("\t|--------3. 退出 --------|\n");
printf("\t|---------------------------|\n");
printf("请输入选项>>>");
// choice = getchar();
// while(getchar()!=10);//吸收垃圾字符
scanf("%d",&choice);
getchar();
switch(choice)
{
case 1:
do_search(&usr,sfd);
break;
case 2:
do_history(&usr,sfd);
break;
case 3:
close(sfd);
exit(0);
break;
default:
printf("输入错误,请重新输入\n");
}
}
return 0;
}
服务器:
#include <stdio.h>
#include <sqlite3.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <unistd.h>
#include <signal.h>
#include <sys/wait.h>
#include<string.h>
#include <time.h>
#define err(msg) do{printf("__%d__",__LINE__);perror(msg);return -1;}while(0)
#define PORT 8888
#define IP "192.168.3.92"//本地测试 127.0.0.1 ifconfig 192.168.3.92
typedef void (*sighandler_t)(int);
typedef struct
{
char flag;
char name[20];
char text[128];
}msg;
char mean[32]="";
int do_register(msg *usr,int afd,sqlite3* db)
{
char sql[256] = "" ;
// sprintf(sql,"%s(%d,'%s',%d);","insert into values",id,name,score);
sprintf(sql,"insert into usr values('%s','%s');",usr->name,usr->text);
char* errmsg = NULL;
if(sqlite3_exec(db,sql,NULL,NULL,&errmsg) != SQLITE_OK)//约束条件失败--name primary key 阻塞函数recv
{
fprintf(stderr, "__%d__ sqlite3_exec:%s\n", __LINE__, errmsg);
strcpy(usr->text,"usr name already exist");
printf("usr name already exist\n");
}
else
{
printf("registeration is ok\n");
strcpy(usr->text,"usr name registeration successed");
}
if(send(afd,usr,sizeof(msg),0)<0)err("send");
if(recv(afd,usr,sizeof(msg),0)<0)err("recv");
return 0;
}
int do_login(msg *usr,int afd,sqlite3* db)
{
sqlite3* db_delete= NULL;
char sql[256] ="";
char* errmsg = NULL;
char **pres=NULL;
int row,column;
sprintf(sql,"select * from usr where name='%s' and password='%s';",usr->name,usr->text);//select * from usr where name='' and password='';
//对比用户数据库--返回值 sqlite3_get_table
if(sqlite3_get_table(db, sql,&pres,&row,&column, &errmsg) != SQLITE_OK)
{
fprintf(stderr, "__%d__ sqlite3_get_table:%s\n", __LINE__, errmsg);
return -1;
}
//查到数据
if(row==1)
{
printf("login is ok\n");
bzero(usr->text,sizeof(usr->text));
strcpy(usr->text,"ok");
}
else{
printf("login is failed\n");
strcpy(usr->text,"usr name or password inputs error!");
}
if(send(afd,usr,sizeof(msg),0)<0)err("send");
if(recv(afd,usr,sizeof(msg),0)<0)err("recv");
return 0;
}
//功能:查询表格中的内容
int callback_s(void* arg ,int columns, char** column_text, char** column_name)
{
//查询结果的列数
// printf("columns = %d __%d__\n", columns, __LINE__);
//打印单词和解释
for(int i=1; i<columns; i+=2)
{
// printf("%s\t", *(column_text+i));
strcpy(mean,*(column_text+i));
}
printf("\n");
return 0; //成功返回0,失败返回非0;
}
int do_search(msg *usr,int afd,sqlite3* db)
{
char sql[256] ="",sql_h[256]="",word[64]="",TIME[32]="";
time_t t;
struct tm *info = NULL;
int flag=0;
strcpy(word,usr->text);
t =time(NULL);
info =localtime(&t);
sprintf(TIME,"%d-%02d-%02d %02d:%02d:%02d",info->tm_year+1900, info->tm_mon+1, info->tm_mday,info->tm_hour, info->tm_min, info->tm_sec);
sprintf(sql,"select * from dict where word='%s';",usr->text);
//查询dict数据库,如何获取数据库里的单词解释--回调函数
char* errmsg = NULL;
if(sqlite3_exec(db, sql,callback_s,&flag, &errmsg) != SQLITE_OK)//exec 展示需要回调函数
{
fprintf(stderr, "__%d__ sqlite3_exec:%s\n", __LINE__, errmsg);
return -1;
}
bzero(usr->text,sizeof(usr->text));//清空 解释
strcpy(usr->text,mean);
//每查找一次,向历史数据库插入一次。
sprintf(sql_h,"insert into history values('%s','%s','%s',\'%s\');",usr->name,word,mean,TIME);
bzero(mean,sizeof(mean));
bzero(word,sizeof(word));
if(sqlite3_exec(db,sql_h,NULL,NULL,&errmsg) != SQLITE_OK)
{
fprintf(stderr, "__%d__ sqlite3_exec:%s\n", __LINE__, errmsg);
}
if(send(afd,usr,sizeof(msg),0)<0)err("send");
if(recv(afd,usr,sizeof(msg),0)<0)err("recv");
return 0;
}
int callback_h(void* arg ,int columns, char** column_text, char** column_name)
{
//name word mean date
int afd=*(int *)arg;
msg usr;
char word[64]="",TIME[32]="";
bzero(usr.text,sizeof(usr.text));
bzero(usr.name,sizeof(usr.name));
for(int i=0; i<columns; i++)
{
switch(i)
{
case 0: {strcpy(usr.name,*(column_text));}break;
case 1: {strcpy(word,*(column_text+1));}break;
case 2: {strcpy(mean,*(column_text+2));}break;
case 3: {strcpy(TIME,*(column_text+3));}break;
}
}
sprintf(usr.text,"%s:%s\t%s\t%s",usr.name,word,mean,TIME);
printf("%s\n",usr.text);
if(send(afd,&usr,sizeof(msg),0)<0)err("send");
return 0; //成功返回0,失败返回非0;
}
int do_history(msg* usr,int afd,sqlite3* db)
{
char sql[256]="";
sprintf(sql,"select * from history where name='%s';",usr->name);
char* errmsg = NULL;
//get_table --行数 列数/ exec-- 列数,内容
if(sqlite3_exec(db, sql,callback_h,&afd, &errmsg) != SQLITE_OK)//exec 展示需要回调函数
{
fprintf(stderr, "__%d__ sqlite3_get_table:%s\n", __LINE__, errmsg);
return -1;
}
printf("this is all\n");
//结束标志发给客户端
usr->text[0]='\0';
if(send(afd,usr,sizeof(msg),0)<0)err("send");
exit(0);
//return 0;
}
void handler(int sig)
{
while(waitpid(-1,NULL,WNOHANG)>0);
}
int main(int argc, const char *argv[])
{
//TCP_select模型
//创建套接字
int afd,sfd=socket(AF_INET,SOCK_STREAM,0);
if(sfd<0)err("socket");
//允许端口快速重用
int reuse = 1;
if(setsockopt(sfd, SOL_SOCKET, SO_REUSEADDR, &reuse, sizeof(reuse)) < 0)err("setsockopt");
//服务器用户地址信息
struct sockaddr_in sin;
sin.sin_family=AF_INET;
sin.sin_port=htons(PORT);
sin.sin_addr.s_addr=inet_addr(IP);//<<inet_addr
//绑定
if(bind(sfd,(struct sockaddr*)&sin,sizeof(sin))<0)err("bind");
//监听listen 同一瞬间允许建立10个连接
if(listen(sfd,10)<0)err("listen");
//获取客户端信息
struct sockaddr_in cin;
socklen_t addrlen=sizeof(cin);
//僵尸进程
if(SIG_ERR==signal(SIGCHLD,handler))err("signal");
//打开数据库
sqlite3* db = NULL;
if(sqlite3_open("./my.db", &db) != SQLITE_OK)
{
printf("err_code:%d\n", sqlite3_errcode(db));
printf("errmsg:%s\n", sqlite3_errmsg(db));
fprintf(stderr, "__%d__ sqlite3_open failed\n", __LINE__);
return -1;
}
//创建一个表格
char* sql_dict = "create table if not exists dict (word char,mean char);" ;
char* sql_usr = "create table if not exists usr (name char primary key,password char);" ;
char* sql_history = "create table if not exists history (name char,word char,mean char,time char);" ;//历史数据库
char* errmsg = NULL;
if(sqlite3_exec(db, sql_usr, NULL, NULL, &errmsg) != SQLITE_OK)
{
fprintf(stderr, "__%d__ sqlite3_exec:%s\n", __LINE__, errmsg);
return -1;
}
if(sqlite3_exec(db, sql_history, NULL, NULL, &errmsg) != SQLITE_OK)
{
fprintf(stderr, "__%d__ sqlite3_exec:%s\n", __LINE__, errmsg);
return -1;
}
if(sqlite3_exec(db, sql_dict, NULL, NULL, &errmsg) != SQLITE_OK)
{
fprintf(stderr, "__%d__ sqlite3_exec:%s\n", __LINE__, errmsg);
return -1;
}
msg usr;
char choose = 0;
int res=0,pid;
while(1)
{
if((afd=accept(sfd,(struct sockaddr*)&sin,&addrlen))<0)err("accept");
pid=fork();
if(pid>0)
{
//接收客户端消息
close(afd);
}
else if(pid==0)
{
memset(&usr,0,sizeof(msg));
//处理客户端消息
res=recv(afd,&usr,sizeof(usr),0);
if(res<0)err("recv");
printf("flag=%c\n",usr.flag);
while(res>0)
{
switch(usr.flag)
{
case 'R':do_register(&usr,afd,db);break;
case 'L':do_login(&usr,afd,db);break;
case 'S':do_search(&usr,afd,db);break;
case 'H':do_history(&usr,afd,db);break;
default:printf("error\t261\n");
}
}
}
}
return 0;
}