在线英英词典
项目功能描述
用户注册和登录验证
服务器端将用户信息和历史记录保存在数据库中。客户端输入用户名和密码,服务器端在数据库中查找、匹配,返回结果
单词在线翻译
根据客户端输入的单词在字典文件中搜索
历史记录查询
项目分析
代码实现
gcc sqlite3.c server.c -o server -lpthread -lsqlite3 -ldl
./server 192.168.232.128 1234```
```c
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h> /* See NOTES */
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <string.h>
#include <unistd.h>
#include <sqlite3.h>
#include <signal.h>
#include <time.h>
#define N 32
#define R 1 // user - register
#define L 2 // user - login
#define Q 3 // user - query
#define H 4 // user - history
#define DATABASE "my.db"
// 定义通信双方的信息结构体
typedef struct {
int type;
char name[N];
char data[256];
}MSG;
int do_client(int acceptfd, sqlite3 *db);
void do_register(int acceptfd, MSG *msg, sqlite3 *db);
int do_login(int acceptfd, MSG *msg, sqlite3 *db);
int do_query(int acceptfd, MSG *msg, sqlite3 *db);
int do_history(int acceptfd, MSG *msg, sqlite3 *db);
int history_callback(void* arg,int f_num,char** f_value,char** f_name);
int do_searchword(int acceptfd, MSG *msg, char word[]);
int get_date(char *date);
// ./server 192.168.3.196 10000
int main(int argc, const char *argv[])
{
int sockfd;
struct sockaddr_in serveraddr;
int n;
MSG msg;
sqlite3 *db;
int acceptfd;
pid_t pid;
if(argc != 3)
{
printf("Usage:%s serverip port.\n", argv[0]);
return -1;
}
//打开数据库
if(sqlite3_open(DATABASE, &db) != SQLITE_OK)
{
printf("%s\n", sqlite3_errmsg(db));
return -1;
}
else
{
printf("open DATABASE success.\n");
}
if((sockfd = socket(AF_INET, SOCK_STREAM,0)) < 0)
{
perror("fail to socket.\n");
return -1;
}
bzero(&serveraddr, sizeof(serveraddr));
serveraddr.sin_family = AF_INET;
serveraddr.sin_addr.s_addr = inet_addr(argv[1]);
serveraddr.sin_port = htons(atoi(argv[2]));
if(bind(sockfd, (struct sockaddr *)&serveraddr, sizeof(serveraddr)) < 0)
{
perror("fail to bind.\n");
return -1;
}
// 将套接字设为监听模式
if(listen(sockfd, 5) < 0)
{
printf("fail to listen.\n");
return -1;
}
//处理僵尸进程
signal(SIGCHLD, SIG_IGN);
while(1)
{
if((acceptfd = accept(sockfd, NULL, NULL)) < 0)
{
perror("fail to accept");
return -1;
}
if((pid = fork()) < 0)
{
perror("fail to fork");
return -1;
}
else if(pid == 0) // 儿子进程
{
//处理客户端具体的消息
close(sockfd);
do_client(acceptfd, db);
}
else // 父亲进程,用来接受客户端的请求的
{
close(acceptfd);
}
}
return 0;
}
int do_client(int acceptfd, sqlite3 *db)
{
MSG msg;
while(recv(acceptfd, &msg, sizeof(msg), 0) > 0)
{
printf("type:%d\n", msg.type);
switch(msg.type)
{
case R:
do_register(acceptfd, &msg, db);
break;
case L:
do_login(acceptfd, &msg, db);
break;
case Q:
do_query(acceptfd, &msg, db);
break;
case H:
do_history(acceptfd, &msg, db);
break;
default:
printf("Invalid data msg.\n");
}
}
printf("client exit.\n");
close(acceptfd);
exit(0);
return 0;
}
void do_register(int acceptfd, MSG *msg, sqlite3 *db)
{
char * errmsg;
char sql[128];
sprintf(sql, "insert into usr values('%s', %s);", msg->name, msg->data);
printf("%s\n", sql);
if(sqlite3_exec(db,sql, NULL, NULL, &errmsg) != SQLITE_OK)
{
printf("%s\n", errmsg);
strcpy(msg->data, "usr name already exist.");
}
else
{
printf("client register ok!\n");
strcpy(msg->data, "OK!");
}
if(send(acceptfd, msg, sizeof(MSG), 0) < 0)
{
perror("fail to send");
return ;
}
return ;
}
int do_login(int acceptfd, MSG *msg , sqlite3 *db)
{
char sql[128] = {};
char *errmsg;
int nrow;
int ncloumn;
char **resultp;
sprintf(sql, "select * from usr where name = '%s' and pass = '%s';", msg->name, msg->data);
printf("%s\n", sql);
if(sqlite3_get_table(db, sql, &resultp, &nrow, &ncloumn, &errmsg)!= SQLITE_OK)
{
printf("%s\n", errmsg);
return -1;
}
else
{
printf("get_table ok!\n");
}
// 查询成功,数据库中拥有此用户
if(nrow == 1)
{
strcpy(msg->data, "OK");
send(acceptfd, msg, sizeof(MSG), 0);
return 1;
}
if(nrow == 0) // 密码或者用户名错误
{
strcpy(msg->data,"usr/passwd wrong.");
send(acceptfd, msg, sizeof(MSG), 0);
}
return 0;
}
int do_searchword(int acceptfd, MSG *msg, char word[])
{
FILE * fp;
int len = 0;
char temp[512] = {};
int result;
char *p;
//打开文件,读取文件,进行比对
if((fp = fopen("dict.txt", "r")) == NULL)
{
perror("fail to fopen.\n");
strcpy(msg->data, "Failed to open dict.txt");
send(acceptfd, msg, sizeof(MSG), 0);
return -1;
}
//打印出,客户端要查询的单词
len = strlen(word);
printf("%s , len = %d\n", word, len);
//读文件,来查询单词
while(fgets(temp, 512, fp) != NULL)
{
// printf("temp:%s\n", temp);
// abandon ab
result = strncmp(temp,word,len);
if(result < 0)
{
continue;
}
if(result > 0 || ((result == 0) && (temp[len]!=' ')))
{
break;
}
// 表示找到了,查询的单词
p = temp + len; // abandon v.akdsf dafsjkj
// printf("found word:%s\n", p);
while(*p == ' ')
{
p++;
}
// 找到了注释,跳跃过所有的空格
strcpy(msg->data, p);
printf("found word:%s\n", msg->data);
// 注释拷贝完毕之后,应该关闭文件
fclose(fp);
return 1;
}
fclose(fp);
return 0;
}
int get_date(char *date)
{
time_t t;
struct tm *tp;
time(&t);
//进行时间格式转换
tp = localtime(&t);
sprintf(date, "%d-%d-%d %d:%d:%d", tp->tm_year + 1900, tp->tm_mon+1, tp->tm_mday,
tp->tm_hour, tp->tm_min , tp->tm_sec);
printf("get date:%s\n", date);
return 0;
}
int do_query(int acceptfd, MSG *msg , sqlite3 *db)
{
char word[64];
int found = 0;
char date[128] = {};
char sql[128] = {};
char *errmsg;
//拿出msg结构体中,要查询的单词
strcpy(word, msg->data);
found = do_searchword(acceptfd, msg, word);
printf("查询一个单词完毕.\n");
// 表示找到了单词,那么此时应该将 用户名,时间,单词,插入到历史记录表中去。
if(found == 1)
{
// 需要获取系统时间
get_date(date);
sprintf(sql, "insert into record values('%s', '%s', '%s')", msg->name, date, word);
if(sqlite3_exec(db, sql, NULL, NULL, &errmsg) != SQLITE_OK)
{
printf("%s\n", errmsg);
return -1;
}
else
{
printf("Insert record done.\n");
}
}
else //表示没有找到
{
strcpy(msg->data, "Not found!");
}
// 将查询的结果,发送给客户端
send(acceptfd, msg, sizeof(MSG), 0);
return 0;
}
// 得到查询结果,并且需要将历史记录发送给客户端
int history_callback(void* arg,int f_num,char** f_value,char** f_name)
{
// record , name , date , word
int acceptfd;
MSG msg;
acceptfd = *((int *)arg);
sprintf(msg.data, "%s , %s", f_value[1], f_value[2]);
send(acceptfd, &msg, sizeof(MSG), 0);
return 0;
}
int do_history(int acceptfd, MSG *msg, sqlite3 *db)
{
char sql[128] = {};
char *errmsg;
sprintf(sql, "select * from record where name = '%s'", msg->name);
//查询数据库
if(sqlite3_exec(db, sql, history_callback,(void *)&acceptfd, &errmsg)!= SQLITE_OK)
{
printf("%s\n", errmsg);
}
else
{
printf("Query record done.\n");
}
// 所有的记录查询发送完毕之后,给客户端发出一个结束信息
msg->data[0] = '\0';
send(acceptfd, msg, sizeof(MSG), 0);
return 0;
}
代码分析总结
- 代码功能
这是一个基于 TCP 的单词查询服务器,支持以下功能:
用户注册(R):将用户名和密码存入 SQLite 数据库。
用户登录(L):验证用户名和密码。
单词查询(Q):从本地文件 dict.txt 中查询单词释义,并记录查询历史。
历史记录查询(H):返回用户的所有查询记录(时间 + 单词)。
2. 代码结构
模块 功能
主函数 (main) 初始化数据库、创建监听套接字、处理客户端连接(多进程模型)。
do_client 接收客户端请求,根据类型分发到不同处理函数(注册、登录、查询、历史记录)。
do_register 用户注册逻辑,插入数据到 usr 表。
do_login 用户登录验证,查询 usr 表匹配记录。
do_query 查询单词释义,记录到 record 表。
do_history 查询用户历史记录,通过回调函数逐条发送。
do_searchword 从 dict.txt 文件中查找单词释义。
- 关键实现细节
多进程模型
父进程监听连接,子进程处理客户端请求,避免阻塞。
if ((pid = fork()) == 0) {
close(sockfd);
do_client(acceptfd, db);
}
SQLite 操作
使用 sqlite3_exec 和 sqlite3_get_table 执行 SQL 语句,存储用户和查询记录。
sprintf(sql, "insert into usr values('%s', %s);", msg->name, msg->data);
sqlite3_exec(db, sql, NULL, NULL, &errmsg);
单词查询逻辑
通过遍历 dict.txt 文件逐行匹配单词,使用 strncmp 快速定位。
while (fgets(temp, 512, fp) != NULL) {
result = strncmp(temp, word, len);
// ... 匹配处理
}
历史记录回调
使用 sqlite3_exec 的回调函数逐行发送历史记录。
int history_callback(void* arg, ...) {
send(acceptfd, &msg, sizeof(MSG), 0);
return 0;
}
- 流程图
+-----------------------+
| 主进程 (监听) |
+-----------------------+
|
| accept()
v
+-----------------------+
| 子进程 (处理请求) |
+-----------------------+
|
| do_client()
v
+-----------------------+
| 根据消息类型调用处理函数 |
| (R/L/Q/H) |
+-----------------------+
|
| 数据库/文件操作
v
+-----------------------+
| 返回结果给客户端 |
+-----------------------+
- 总结
该代码实现了一个基础的网络单词查询服务,但存在安全性和健壮性缺陷。通过优化 SQL 操作、完善错误处理、改进进程模型,可显著提升稳定性和安全性。