HTML Client : demo.html
<!DOCTYPE html>
<html>
<head>
<script src="javascript/jquery/jquery-1.9.1.min.js"></script>
<script>
http_post = function(){
var data = $.ajax({
type: "POST",
async: false,
url: 'http://10.30.130.125/demo.php',
data: ({request : {ID:"hello world"} })
}).responseText;
//return eval('(' +data +')');
//eval('(' +data +')');
//alert (data);
document.getElementById("demo").innerHTML=data ;
<!---document.getElementById("demo").innerHTML="Hello World"; -->
}
</script>
</head>
<body>
<p>Click the button to trigger a function.</p>
<button onclick="http_post()">Click me</button>
<p id="demo"></p>
</body>
</html>
PHP File: demo.php
<?php
error_reporting(E_ALL);
$in_str = "None" ;
if ($_POST) {
//var_dump($_POST['request']) ;
$in_str = '{"demo":"'.$_POST["request"]['ID'].'"}' ;
//$in_str = $_POST["request"] ;
}
$service_port = '5000' ;
$address = '10.30.130.170' ;
/* Create a TCP/IP socket. */
$socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
$result = socket_connect($socket, $address, $service_port);
echo $in_str ;
/* write into TCP/IP socket.*/
socket_write($socket, $in_str, strlen($in_str));
/* read from TCP/IP socket. */
$out = socket_read($socket, 4096);
/* Closing socket... */
socket_close($socket);
//$out = "{\"a\":1 }" ;
header('Access-Control-Allow-Origin: *');
echo $out;
//echo '{"hi": 1 }';
/*echo "{\"a\":1 }" ;*/
?>
C Server Socket code below:
#include < sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <errno.h>
#include <string.h>
#include <sys/types.h>
int main(int argc, char *argv[])
{
int listenfd = 0, connfd = 0;
struct sockaddr_in serv_addr;
char recvBuff[1024];
int data = 65;
int n ;
time_t ticks;
listenfd = socket(AF_INET, SOCK_STREAM, 0);
memset(&serv_addr, '0', sizeof(serv_addr));
memset(&recvBuff, '0', sizeof(recvBuff));
serv_addr.sin_family = AF_INET;
serv_addr.sin_addr.s_addr = htonl(INADDR_ANY);
serv_addr.sin_port = htons(5000);
bind(listenfd, (struct sockaddr*)&serv_addr,
sizeof(serv_addr));
listen(listenfd, 10);
while(1)
{
connfd =
accept(listenfd, (struct sockaddr*)NULL, NULL);
n = read(connfd,
recvBuff, sizeof(recvBuff)) ;
recvBuff[n] = 0;
printf("Recieved
Client request.\n") ;
printf("%s\n"
, recvBuff) ; // Received string will be ID => {"demo":"hello world"}
if(strstr(recvBuff, "hello world")== 0)
{
write(connfd,
&data, sizeof(data));
close(connfd);
}
else
{
printf("%s\n" , recvBuff) ;
}
data++ ;
}
}