Thread: TCP Server cannot save buffer data to mysql !

  1. #1
    Registered User
    Join Date
    Sep 2010
    Posts
    3

    Unhappy TCP Server cannot save buffer data to mysql !

    I'm developing a TCP Server that can save data to mysql.
    The problem is "buf" cannot be save/insert into the field of "rawdata" in mysql. But "name" work perfectly can be save/insert into the field of "rawdata" in mysql. Do u know what is the problem is? and how to fix that? I'm very glad if u can help me.
    below is the code.

    to compile in unix / linux :
    gcc -o tcpecho $(mysql_config --cflags) tcpecho.c $(mysql_config --libs)

    need mysql C api connector (if u don't have)
    MySQL :: Download Connector/C

    Here the sql file :

    Code:
    -- phpMyAdmin SQL Dump
    -- version 3.2.4
    -- http://www.phpmyadmin.net
    --
    -- Host: localhost
    -- Generation Time: Sep 19, 2010 at 10:29 AM
    
    
    SET SQL_MODE="NO_AUTO_VALUE_ON_ZERO";
    
    
    /*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
    /*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;
    /*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;
    /*!40101 SET NAMES utf8 */;
    
    --
    -- Database: `mydatabase`
    --
    
    -- --------------------------------------------------------
    
    --
    -- Table structure for table `lastpos`
    --
    
    CREATE TABLE IF NOT EXISTS `lastpos` (
      `id` bigint(255) NOT NULL auto_increment,
      `unit_id` varchar(255) NOT NULL,
      `lat` varchar(255) NOT NULL,
      `lon` varchar(255) NOT NULL,
      `type` varchar(255) NOT NULL,
      `rawdata` varchar(255) NOT NULL,
      PRIMARY KEY  (`id`)
    ) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ;
    
    --
    -- Dumping data for table `lastpos`
    --
    Here the C code :
    Code:
    #ifndef unix
    #define WIN32
    #include <windows.h>
    #include <winsock.h> 
    #else
    #define closesocket close
    #include <sys/types.h>
    #include <sys/socket.h>
    #include <netinet/in.h>
    #include <netdb.h>
    #endif
    
    #include <stdio.h>
    #include <string.h>
    #include <my_global.h>
    #include <mysql.h>
    
    #define PROTOPORT       6500            /* default protocol port number */
    #define QLEN            6               /* size of request queue        */
    
    int     visits      =   0;              /* counts client connections    */
    /*------------------------------------------------------------------------
     * Program:   server
     *
     * Purpose:   allocate a socket and then repeatedly execute the following:
     *              (1) wait for the next connection from a client
     *              (2) send a short message to the client
     *              (3) close the connection
     *              (4) go back to step (1)
     *
     * Syntax:    server [ port ]
     *
     *               port  - protocol port number to use
     *
     * Note:      The port argument is optional.  If no port is specified,
     *            the server uses the default given by PROTOPORT.
     *
     * The EchoServer program can handle one single client at a time. For instance, if you try to run concurrently 
     * two echo clients (in two separate windows), only one client can talk to the server; the second client can start talking to the server only after the 
     * first client finishes its execution. Modify the code for the echo server to support multiple clients concurrently. 
     * The server should spawn a new thread each time it receives a connection request from a client. 
     * It is the thread now that handles (services) the client, while the server goes back to listening for new incoming connections from other clients.
     
    
     *------------------------------------------------------------------------
     */
    main(argc, argv)
    int     argc;
    char    *argv[];
    {
            struct  hostent  *ptrh;  /* pointer to a host table entry       */
            struct  protoent *ptrp;  /* pointer to a protocol table entry   */
            struct  sockaddr_in sad; /* structure to hold server's address  */
            struct  sockaddr_in cad; /* structure to hold client's address  */
            int     sd, sd2;         /* socket descriptors                  */
            int     port;            /* protocol port number                */
            int     alen;            /* length of address                   */
            char    buf[1000];       /* buffer for string the server sends  */
            int     n;               /* number of characters received       */ 
            int optval = 1;          /* options set by setsockopt           */
            char    query[4096];
            char    name[] = "test i can save this in mysql";
    
    #ifdef WIN32
            WSADATA wsaData;
            WSAStartup(0x0101, &wsaData);
    #endif
            memset((char *)&sad, 0, sizeof(sad)); /* clear sockaddr structure */
            sad.sin_family = AF_INET;             /* set family to Internet     */
            sad.sin_addr.s_addr = INADDR_ANY;     /* set the local IP address   */
    
            /* Check command-line argument for protocol port and extract    */
            /* port number if one is specified.  Otherwise, use the default */
            /* port value given by constant PROTOPORT                       */
    
            if (argc > 1) {                 /* if argument specified        */
                    port = atoi(argv[1]);   /* convert argument to binary   */
            } else {
                    port = PROTOPORT;       /* use default port number      */
            }
            if (port > 0)                   /* test for illegal value       */
                    sad.sin_port = htons((u_short)port);
            else {                          /* print error message and exit */
                    fprintf(stderr,"Bad port number %s\n",argv[1]);
                    exit(1);
            }
    
            /* Map TCP transport protocol name to protocol number */
    
            if ( ((int)(ptrp = getprotobyname("tcp"))) == 0) {
                    fprintf(stderr, "cannot map \"tcp\" to protocol number");
                    exit(1);
            }
    
            /* Create a socket */
    
            sd = socket(AF_INET, SOCK_STREAM, ptrp->p_proto);
            if (sd < 0) {
                    fprintf(stderr, "Socket creation failed\n");
                    exit(1);
            }
    
            /* Eliminate "Address already in use" error from bind. */
    
            if (setsockopt(sd, SOL_SOCKET, SO_REUSEADDR,
                       (const void *)&optval , sizeof(int)) < 0)
            return -1;
    
    
            /* Bind a local address to the socket */
    
            if (bind(sd, (struct sockaddr *)&sad, sizeof(sad)) < 0) {
                    fprintf(stderr,"Bind failed\n");
                    exit(1);
            }
    
            /* Specify size of request queue */
    
            if (listen(sd, QLEN) < 0) {
                    fprintf(stderr,"Listen failed\n");
                    exit(1);
            }
    
    
                /* sql connection */
                 MYSQL *conn;
                 conn = mysql_init(NULL);
                 mysql_real_connect(conn, "localhost", "root", "mypassword", "mydatabase", 0, NULL, 0); 
    
           
            /* Main server loop - accept and handle requests */
    
            while (1) {
                    alen = sizeof(cad);
                    if ( (sd2 = accept(sd, (struct sockaddr *)&cad, &alen)) < 0) {
                            fprintf(stderr, "Accept failed\n");
                            exit(1);
                    }
                    n = recv(sd2, buf, sizeof(buf), 0);
                    while (n > 0)
                    {
                        //send(sd2, buf, n, 0);
                        n = recv(sd2, buf, sizeof(buf), 0);
    
             
                        printf("data : %s\n",buf);
                      //sprintf(query,"INSERT INTO lastpos (id,unit_id,lat,lon,type,rawdata) VALUES('','','','','','%s')",name);
                        sprintf(query,"INSERT INTO lastpos (id,unit_id,lat,lon,type,rawdata) VALUES('','','','','','%s')",buf);
                        mysql_query(conn,query);
    
    
                    }
                    mysql_close(conn); /*mysql close connection*/
                    closesocket(sd2);
                 
            }
    }
    p/s : please note, i'm modifying the code from other example to make it work with mysql. Anyone that can help me i hope u can be the best helpful person. I will donate to your paypal if u can get it to work.
    Last edited by syedmuhd; 09-18-2010 at 08:52 PM.

  2. #2
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,656
    Well there is:

    a) recv() does NOT append a \0 to make it a proper string
    b) recv() does NOT guarantee to receive the whole message
    c) you're NOT actually checking the return result to see how much data arrived (only 'some' data).
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.

  3. #3
    Registered User
    Join Date
    Sep 2010
    Posts
    3
    Quote Originally Posted by Salem View Post
    Well there is:

    a) recv() does NOT append a \0 to make it a proper string
    b) recv() does NOT guarantee to receive the whole message
    c) you're NOT actually checking the return result to see how much data arrived (only 'some' data).
    Well, how to fix that? really hope if u can make it detail.

  4. #4
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,656
    > Today, 07:58 PM
    ...
    > Today, 08:02 PM
    A whole FOUR MINUTES!
    Yeah, you really put yourself out there in trying to figure something out what needs to be done.

    Man, your mouse must be smokin' with the speed you hit the quote reply and send.

    Sheesh!
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.

  5. #5
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,656
    Too busy scanning for other places to post no doubt....
    TCP Server cannot save buffer data to mysql ! - Dev Shed
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.

  6. #6
    Registered User
    Join Date
    Sep 2010
    Posts
    3
    Quote Originally Posted by Salem View Post
    Too busy scanning for other places to post no doubt....
    TCP Server cannot save buffer data to mysql ! - Dev Shed
    Please help, i'm serious in this matter. i will donate to your paypal if u can get it to work.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Memory Leak in AppWizard-Generated Code
    By jrohde in forum Windows Programming
    Replies: 4
    Last Post: 05-19-2010, 04:24 PM
  2. Does realloc save the previous buffer data?
    By Niara in forum C Programming
    Replies: 6
    Last Post: 07-23-2008, 04:40 AM
  3. Client works on a LAN but don't send all the data
    By Niara in forum Networking/Device Communication
    Replies: 9
    Last Post: 01-04-2007, 04:44 PM
  4. Tetris Questions
    By KneeGrow in forum Game Programming
    Replies: 19
    Last Post: 10-28-2003, 11:12 PM
  5. socket question
    By Unregistered in forum C Programming
    Replies: 3
    Last Post: 07-19-2002, 01:54 PM