这两天写了一个小项目,但是出现了一点小问题,在线请求各位大咖不吝赐教。
服务器端查找所有信息,并把查到的信息发送到客户端
//全部查询的回调函数
int callback(void * prama,int f_num,char * f_value[],char * f_name[])
{
int newfd = *(int *)prama;
int i=0;
char buf[1000] = {'\0'};
//列名
for(i=0;i<f_num-1;i++)
{
printf("%20s",f_name[i]);
}
printf("\n");
//列值
for(i=0;i<f_num;i++)
{
printf("%20s",f_value[i]);
sprintf(buf+strlen(buf), "%15s", f_value[i]);
}
printf("\n");
usleep(100);
//发送给客户端
int n = send(newfd, buf, strlen(buf), 0);
printf("回调函数发送,n = %d\n", n);
if(n < 0)
{
perror("send error");
return -1;
}
bzero(buf,sizeof(buf));
//printf("select_all ok!\n");
return 0;
}
//全部查询
int select_all(int newfd, sqlite3 * mydb,const char * tbname)
{
char end[10] = {'\0'};
strcpy(end, "over");
char sql[100] = {'\0'};
sprintf(sql,"select * from %s",tbname);
printf("%s\n",sql);
int ret=0;
char * errmsg=NULL;
//参数3:函数指针,函数名可以随意取,但函数类型必须一直
ret=sqlite3_exec(mydb, sql, callback, &newfd, &errmsg);
if(ret!=SQLITE_OK)
{
printf("select error:%s\n",errmsg);
return -1;
}
sleep(1);
//发送结束命令
int n = send(newfd, end, strlen(end), 0);
printf("all select over = %d\n", n);
if(n < 0)
{
perror("send error");
return -1;
}
return 0;
}
客户端收服务器发过来的消息,并打印出来
//编写一子函数,实现查看所有医生信息
//参数1:newfd套接字
//返回值:成功返回0,失败返回-1
int select_doctors(int newfd)
{
char buf[1000]= {'\0'};
printf("All doctors are as follow\n");
//接受服务器发送的doctor表,并打印
while(1)
{
int n = recv(newfd, buf, sizeof(buf) ,0);
printf("select_doctors n = %d\n", n);
if(n < 0)
{
perror("send error");
return -1;
}
printf("\n%s\n",buf);
int i = 0;
if(strncasecmp(buf, "over", 4) == 0) {
break;//接受到结束的,结束循环
}
}
return 0;
}