Search This Blog

Wednesday, April 7, 2010

Using PHP and C to read data from client and send to server

Once i faced a problem like we have to connect the device(RS232 or serial port) to the client machine and we have to get the data from the client machine to the server when user performs an action like click of a button or blur from a control etc


As if we are using PHP,Apache on linux platform on server and windows for client machine and also the application in which i was trying to add this feature runs on browser 



So what i did is created a 'C' Program complied on different platforms, Program in the RS232 will send the data from the client to the server in particular time interval and the program on the Server will store the incoming data in a text file on the server when user performs action on the client then client request to the server for data and the server gives the data to the client (this is achieved using Ajax) then the data is shown in the desired field after user confirms that it is taken further (stored to database ) 

Data integrity is achieved using the time stamp comparison of data generated from the client and the request given time (time when user performs action)

One thing i want to clarify is while we run applications through browser its not allowed to access the system resources directly 

C program code hints 

Server Code:
sd = socket(AF_INET, SOCK_STREAM, 0);


   /* bind server port */
   servAddr.sin_family = AF_INET;
   servAddr.sin_addr.s_addr = htonl(INADDR_ANY);
   servAddr.sin_port = htons(SERVER_PORT);


   if(bind(sd, (struct sockaddr *) &servAddr, sizeof(servAddr))<0) {
   }


   listen(sd,5);
.
.
.
cliLen = sizeof(cliAddr);
newSd = accept(sd, (struct sockaddr *) &cliAddr, &cliLen); 
.
.
.



strftime(time_data,100," %d-%m-%Y %H:%M:%S ",timeinfo);
        fp=fopen("data4.txt","a");
         fputs(time_data,fp);
fputs(line,fp);
fclose(fp);

Client Code :



h = gethostbyname(HOST);
if(h!=NULL)
{
servAddr.sin_family = h->h_addrtype;
memcpy((char *) &servAddr.sin_addr.s_addr,
h->h_addr_list[0],h->h_length);
servAddr.sin_port = htons(SERVER_PORT);
sd = socket(AF_INET, SOCK_STREAM, 0);


/* bind any port number */
localAddr.sin_family = AF_INET;
localAddr.sin_addr.s_addr = htonl(INADDR_ANY);
localAddr.sin_port = htons(0);


rc = bind(sd, (struct sockaddr *) &localAddr,
sizeof(localAddr));
rc = connect(sd, (struct sockaddr *) &servAddr,
sizeof(servAddr));
fd = open(MODEMDEVICE, O_RDWR | O_NOCTTY );
.
.

res = read(fd,buf,255);   
buf[res]=0;



rc = send(sd, buf, strlen(buf) + 1, 0);


.
.
close(sd);



1 comment:

  1. Thank you very much Sundar sir, I really was happy and interesting about this articles. Thanks lot...

    ReplyDelete