socket C 客户端发送数据到服务端,操作mysql数据库

殷功
2023-12-01

mysql
create table user
(
id int auto_increament primary key,
account varchar(20) not null unique,
passwd varchar(20) not null,
phone varchar(20) not null unique
)
服务端程序

#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<sys/types.h>
#include<sys/socket.h>
#include<netinet/in.h>
#include<arpa/inet.h>
#include<malloc.h>
#include<mysql/mysql.h>

#define server_port "5000"
#define MAXPENDING 1000
#define isntUser -3
#define login_status 1
#define enroll_status 2
#define modifyPasswd_status 3
#define exist_user 1
#define exist_phone 1
int sqlLen;
void dealUserError(const char *msg,const char *detail);
void dealSystemError(const char *msg);
void getClientInformation(int clntSocket,char **recvInfo);
int login(char * temp[10]);
int enroll(char * temp[10]);
int modifyPasswd(char *temp[10]);
void sendInformation(int clntSocket,char *status);

int isExistUser(char *user);
int isExistPhone(char *phone);
int checkRecvString(int clntSocket ,char *temp[10]);
int checkRecvString(int clntSocket ,char *temp[10])
{
    int k = atoi(temp[0]);
    int i = 0;
    for(;temp[i];i++)
        ;
    //printf("string_num = %d\n",i);
    if(k == login_status)
    {
        if(i != 3)
        {
            sendInformation(clntSocket,"error");
            return -1;
        }
    }
    else if(k == enroll_status)
    {
        if(i != 4)
        {
            sendInformation(clntSocket,"error");
            return -1;
        }
    }
    else if(k == modifyPasswd_status)
    {
        if(i != 4)
        {
            sendInformation(clntSocket,"error");
            return -1;
        }
    }
    else
    {
        sendInformation(clntSocket,"error");
        return -1;
    }
    return 1;

}
void executeOper(int clntSocket,char *temp[10]);
void sendInformation(int clntSocket,char *status)
{
    ssize_t num = send(clntSocket,status,strlen(status),0);
    //printf("%d\n",num);
    close(clntSocket);
}
void executeOper(int clntSocket,char *temp[10])
{
    int n = atoi(temp[0]);
    int check_recv_string = checkRecvString(clntSocket,temp);
    if(check_recv_string == -1)
        return ;
    else
    {
        int status;
        if(n == login_status) //表示登录操作
        {
            puts("登录");
        //  nothingOper(temp);
            status = login(temp);

        //printf("status = %d\n",status);
            if(status == isntUser)
                sendInformation(clntSocket,"login_no_exist_user");

            else if(status >= 1)
                sendInformation(clntSocket,"true");
            else
                sendInformation(clntSocket,"login_passwd_error");
        }   
        else if(n == enroll_status) //表示注册
        {
            puts("注册");
            int is_exist_user = isExistUser(temp[1]);
            if(is_exist_user == exist_user)
            {
                sendInformation(clntSocket,"enroll_exit_user");
                return ;
            }
            int is_exist_phone = isExistPhone(temp[3]);
            if(is_exist_phone = exist_phone)
            {
                sendInformation(clntSocket,"enroll_exit_phone");
                return ;
            }
            status = enroll(temp);
            if(status >= 1)
                sendInformation(clntSocket,"true");
            else
                sendInformation(clntSocket,"enrollfalse");
        }   
        else if(n == modifyPasswd_status)//表示密码修改
        {
            puts("密码修改");
            status = login(temp);
            if(status == isntUser)
                sendInformation(clntSocket,"modify_no_exist_user");
            else
            {
                status = modifyPasswd(temp);
                if(status >= 0)
                    sendInformation(clntSocket,"true");
                else
                    sendInformation(clntSocket,"modify_phone_error");
            }
        }
    }
}

int isExistUser(char *user)
{
    int result = 0;
    char *SQL = NULL;
    while(SQL == NULL)
        SQL = (char *)calloc(sqlLen + 50,sizeof(char));

    strcpy(SQL,"select * from user where account = '");
    strcat(SQL,user);
    strcat(SQL,"'");
    MYSQL * conn;
    conn = mysql_init(NULL);
    if(!conn)
    {
        return EXIT_FAILURE;
    }
    int status = -1;
    conn = mysql_real_connect(conn,"localhost","root","123456","user_information",0,NULL,0);
    if(conn)
    {
        MYSQL_RES *res_ptr = NULL;
        MYSQL_ROW sqlrow = 0;
        int res = mysql_query(conn,SQL);
        if(!res)
        {
            res_ptr = mysql_store_result(conn);
            if(res_ptr)
            {
                result = (int)mysql_num_rows(res_ptr);
            }
            mysql_free_result(res_ptr);

        }
    }
    free(SQL);
    mysql_commit(conn);
    mysql_close(conn);
    return result;

}
int isExistPhone(char *phone)
{
    MYSQL *conn;
    conn = mysql_init(NULL);
    if(!conn)
        return EXIT_FAILURE;
    conn = mysql_real_connect(conn,"localhost","root","123456","user_information",0,NULL,0);
    int result = 0;
    if(conn)
    {
        char *SQL = NULL;
        while(SQL == NULL)
            SQL = (char *)calloc(sqlLen + 50,sizeof(char));
        strcpy(SQL,"select * from user where phone = '");
        strcat(SQL,phone);
        strcat(SQL,"'");
        MYSQL_RES *res_ptr = NULL;
        int res = mysql_query(conn,SQL);
        if(!res)
        {
            res_ptr = mysql_store_result(conn);
            if(res_ptr)
            {
                result = (int)mysql_num_rows(res_ptr);
            }
            mysql_free_result(res_ptr);
        }
        free(SQL);


    }
    mysql_commit(conn);
    mysql_close(conn);
    return result;
}
int login(char * temp[10])
{

    MYSQL *conn_ptr;  
    MYSQL_RES *res_ptr;  
    //MYSQL_ROW sqlrow;  
    //MYSQL_FIELD *fd;  
    int res;  

    conn_ptr = mysql_init(NULL);  
    if (!conn_ptr)
        {  
        return EXIT_FAILURE;  
        }
        int status = -1;    
    conn_ptr = mysql_real_connect(conn_ptr, "localhost", "root", "123456", "user_information", 0, NULL, 0);  

    if (conn_ptr) 
    {  
        int result = isExistUser(temp[1]);

        if(result == 0)
        {
            //mysql_free_result(res_ptr);
            mysql_close(conn_ptr);
            return isntUser;
        }

        char *SQL = NULL;
        while(SQL == NULL)
            SQL = (char *)calloc(sqlLen + 50,sizeof(char));


        strcpy(SQL,"select * from user where account = '");
        strcat(SQL,temp[1]);
        strcat(SQL,"' and passwd = '");
        strcat(SQL,temp[2]);
        strcat(SQL,"'");

        res = mysql_query(conn_ptr, SQL); //查询语句  
        if (res)
        {         
            printf("SELECT error:%s\n",mysql_error(conn_ptr));     

        }
            else 
        {        
            res_ptr = mysql_store_result(conn_ptr);             //取出结果集  
            if(res_ptr) 
            {               
                //printf("%lu Rows\n",(unsigned long)mysql_num_rows(res_ptr));   
                status = (int)mysql_num_rows(res_ptr);
                /*j = mysql_num_fields(res_ptr);          
                while((sqlrow = mysql_fetch_row(res_ptr))) 
                    {   //依次取出记录  
                    for(i = 0; i < j; i++)         
                    printf("%s\t", sqlrow[i]);              //输出  
                    printf("\n");          

                }              
                if (mysql_errno(conn_ptr)) 
                {
                    fprintf(stderr,"Retrive error:s\n",mysql_error(conn_ptr));             
                }*/
            }     
            mysql_free_result(res_ptr); 
        }  


        free(SQL);
        mysql_commit(conn_ptr);
        //mysql_close(conn_ptr);
        mysql_close(conn_ptr);
        //printf("status = %d\n",status);
        return status;
    }
}
int modifyPasswd(char *temp[10])
{

    MYSQL  *conn;
    conn = mysql_init(NULL);
    if(!conn)
        return -1;
    conn = mysql_real_connect(conn,"localhost","root","123456","user_information",0,NULL,0);
    if(!conn)
        return -1;
    char *SQL = NULL;
    while(SQL == NULL)
        SQL  = (char *)calloc(sqlLen +50 , sizeof(char));

    strcpy(SQL,"update user set passwd = '");
    strcat(SQL,temp[2]);
    strcat(SQL,"' where phone = '");
    strcat(SQL,temp[3]);
    strcat(SQL,"'");

    mysql_query(conn,SQL);
    int ok = 0;
    ok = mysql_affected_rows(conn);
    //printf("%d\n",ok);
    free(SQL);
    mysql_commit(conn);
    mysql_close(conn);
    return ok;
}

int enroll(char *temp[10])
{
    MYSQL *conn;
    conn = mysql_init(NULL);
    if(!conn)
        return -1;
    conn = mysql_real_connect(conn,"localhost","root","123456","user_information",0,NULL,0);
    if(!conn)
        return -1;

    char *SQL;
    SQL = (char *)calloc(sqlLen+50,sizeof(char));
    strcpy(SQL,"insert into user(account,passwd,phone)values('");
    strcat(SQL,temp[1]);
    strcat(SQL,"','");
    strcat(SQL,temp[2]);
    strcat(SQL,"','");
    strcat(SQL,temp[3]);
    strcat(SQL,"')");
    //puts(SQL);
    mysql_query(conn,SQL);
    int ok = 0;
    ok = mysql_affected_rows(conn);
    //printf("\nok = %d\n",ok);
    //puts(SQL);
    free(SQL);
    mysql_commit(conn);
    mysql_close(conn);
    return ok;
}
void getClientInformation(int clntSocket,char **recvInfo)
{
    char buffer[BUFSIZ];
    memset(buffer,0,sizeof(buffer));
    ssize_t numBytesRcvd = recv(clntSocket,buffer,BUFSIZ,0);

    if(numBytesRcvd < 0)
        dealSystemError("recv() failed!\n");
    //puts(buffer);

    char * tmp;
    sqlLen = strlen(buffer) + 1;
    tmp = (char *)calloc(sqlLen,sizeof(char));

    strcpy(tmp,buffer);
    //puts(buffer);

    *recvInfo = tmp;    
    //send(clntSocket,buffer,strlen(buffer),0);
    //close(clntSocket);
}
void dealSystemError(const char *msg)
{
    perror(msg);
    exit(1);
}
void dealUserError(const char *msg,const char *detail)
{
    fputs(msg,stderr);
    fputs(":",stderr);
    fputs(detail,stderr);
    fputc('\n',stderr);
    exit(1);
}

void main(void)
{
    in_port_t servPort = atoi(server_port);
    int servSock;

    if((servSock = socket(AF_INET,SOCK_STREAM,IPPROTO_TCP))<0)
        dealSystemError("socket() failed!\n");

    struct sockaddr_in servAddr;
    memset(&servAddr,0,sizeof(servAddr));
    servAddr.sin_family = AF_INET;
    servAddr.sin_addr.s_addr = htonl(INADDR_ANY);
    servAddr.sin_port = htons(servPort);

    if(bind(servSock,(struct sockaddr *)&servAddr,sizeof(servAddr)) < 0)
        dealSystemError("bind() failed!\n");

    if(listen(servSock,MAXPENDING)< 0)
        dealSystemError("listen() failed!\n");

    char *recvInfo;
    char *result_gather[10];

    for(;;)
    {
        struct sockaddr_in clientAddr;
        socklen_t clientAddrLen = sizeof(clientAddr);

        int clientSock = accept(servSock,(struct  sockaddr *)&clientAddr,&clientAddrLen);

        if(clientSock < 0)
            dealSystemError("accept() failed!\n");

        char clientName[INET_ADDRSTRLEN];

        if(inet_ntop(AF_INET,&clientAddr.sin_addr.s_addr,clientName,sizeof(clientName)) == NULL)
            puts("Unable to get client address");

        getClientInformation(clientSock,&recvInfo);
        char * tmp;
        int i = 0;
        tmp = recvInfo;
        //puts(recvInfo);
        result_gather[i] = strsep(&tmp,"|");
        while(result_gather[i])
        {
            i++;
            result_gather[i] = strsep(&tmp,"|");
        }

        executeOper(clientSock,result_gather);
        free(recvInfo);
    }
}

客户端程序

#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<unistd.h>
#include<sys/types.h>
#include<sys/socket.h>
#include<netinet/in.h>
#include<arpa/inet.h>
#define server_addr "192.168.1.100"
#define server_port "5000"

int main(int argc,char *argv[])
{
    if(argc < 1)
    {
        puts("<Echo Word>");
        exit(1);
    }
    char *servIP = server_addr;
    char *echoString = argv[1];

    in_port_t servPort = atoi(server_port);
    int sock = socket(AF_INET,SOCK_STREAM,IPPROTO_TCP);
    if(sock < 0)
    {
        puts("socket() failed!\n");
        exit(1);
    }   

    struct sockaddr_in servAddr;
    memset(&servAddr,0,sizeof(servAddr));

    servAddr.sin_family = AF_INET;

    int rtnVal = inet_pton(AF_INET,servIP,&servAddr.sin_addr.s_addr);

    if(rtnVal <= 0)
    {
        puts("inet_pton failed");
        exit(1);
    }

    servAddr.sin_port = htons(servPort);

    if(connect(sock,(struct sockaddr *)&servAddr,sizeof(servAddr)) < 0)
    {
        puts("connect() failed\n");
        exit(1);
    }

    size_t echoStringLen = strlen(echoString);

    ssize_t numBytes = send(sock,echoString,echoStringLen,0);

    if(numBytes < 0)
    {
        puts("send() failed!\n");
        exit(1);
    }
    else if(numBytes != echoStringLen)
    {
        puts("send() expect bytes");
        exit(1);
    }

    unsigned int totalBytesRcvd = 0;
    fputs("Received:",stdout);

    char buffer[BUFSIZ];
    while(totalBytesRcvd > 0)
    {

        numBytes = recv(sock,buffer,BUFSIZ -1 ,0);
        if(numBytes < 0)
        {
            puts("Recv() failed!\n");
            exit(1);
        }
        else if(numBytes == 0)
        {
            puts("connection closed prematurely");
            exit(1);
        }

        totalBytesRcvd += numBytes;
        buffer[numBytes] = '\0';

    }
    int num = recv(sock,buffer,BUFSIZ -1,0);
    buffer[num] = '\0';
    puts(buffer);
    puts("\n");
    //puts(echoString);
    close(sock);
    exit(0);
}

./server
./client “1|kakarot|123456”

 类似资料: