在线词典实现框架:
1、在线词典
2、项目功能描述
3、用户注册和登录验证
4、服务器端将用户信息和历史记录保存在数据库中,客户端输入用户名和密码,服务器端在数据库中查找、匹配,返回结果
5、单次在线翻译
6、根据客户端输入的单次在字典文件中搜索
7、历史记录查询
8、项目分析
服务器流程图:
客户端流程图:
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <string.h>
#include <sqlite3.h>
#include <signal.h>
#include <time.h>
#define N 128
#define R 1
#define L 2
#define O 3
#define M 4
#define Q 5
#define H 6
#define DATABASE "my.db"
typedef struct {
int type;
char name[N];
char data[256];
int flag;
}MSG;
int do_client(int rws, sqlite3 *db);
int do_register(int rws, MSG *msg, sqlite3 *db);
int do_login(int rws, MSG *msg, sqlite3 *db);
int do_logout(int rws, MSG *msg, sqlite3 *db);
int do_modify(int rws,MSG *msg,sqlite3 *db);
int do_query(int rws,MSG *msg,sqlite3 *db);
int do_record(int rws,MSG *msg,sqlite3 *db);
int main(int argc, const char *argv[])
{
int s = -1;
int rws =-1;
struct sockaddr_in addr;
char *errmsg;
pid_t pid;
if(argc != 3){
printf("Usage: %s <ipstr> <port>.\n", argv[0]);
return -1;
}
if((s = socket(AF_INET, SOCK_STREAM, 0)) < 0)
{
perror("socket");
return -1;
}
memset(&addr,0,sizeof(addr));
addr.sin_family = AF_INET;
addr.sin_addr.s_addr = inet_addr(argv[1]);
addr.sin_port = htons(atoi(argv[2]));
if(bind(s, (struct sockaddr *)&addr, sizeof(addr)) < 0)
{
perror("bind");
goto ERR_STEP;
}
if(listen(s, 10) < 0)
{
perror("listen");
goto ERR_STEP;
}
int on = 1;
if(setsockopt(s, SOL_SOCKET, SO_REUSEADDR, &on, sizeof(on)) == -1)
{
perror("setsockopt");
return -1;
}
sqlite3 *db;
if(sqlite3_open(DATABASE, &db) != SQLITE_OK)
{
printf("%s\n", sqlite3_errmsg(db));
return -1;
}
else
{
printf("open Database success\n");
}
char sql[256]="create table if not exists stu(name text,passwd text);";
printf("sql=%s\n",sql);
if(sqlite3_exec(db,sql,NULL,NULL,&errmsg)!=0)
{
fprintf(stderr,"create table fail! %s\n",errmsg);
return -1;
}
char sql_history[256]="create table if not exists record(name text,datetime text,word text);";
printf("sql_history=:%s\n",sql_history);
if(sqlite3_exec(db,sql_history,NULL,NULL,&errmsg)!=0)
{
fprintf(stderr,"create table fail! %s\n",errmsg);
return -1;
}
printf("-------------------准备事项均已成功创建!-------------------------\n");
printf("-------------------接下来等待客户链接请求-------------------------\n");
signal(SIGCHLD, SIG_IGN);
while(1)
{
printf("wait for client...\n");
#if 0
struct sockaddr_in cliaddr;
socklen_t clilen=sizeof(cliaddr);
rws=accept(s,(struct sockaddr*)&cliaddr,&clilen);
char buf[INET_ADDRSTRLEN]={
};
if(inet_ntop(AF_INET,&cliaddr.sin_addr.s_addr,buf,INET_ADDRSTRLEN))
{
printf("client ip:%s ",buf);
}
printf("port:%u\n",ntohs(cusaddr.sin_port));
#endif
#if 1
if((rws = accept(s, NULL, NULL)) < 0)
{
perror("accept");
exit(-1);
}
#endif
if((pid = fork()) < 0)
{
perror("fork");
exit(-1);
}
else if(pid == 0)
{
close(s);
do_client(rws, db)