Question

The idea is to connect PHP webpage and C program via TCP socket so, that webpage waits for connection from C program and receives data as soon as connection established. The code of PHP socket connection and data receiving is below:

PHP(socketRead.php):

 $address = 'localhost'; 
  $port = 5001; 
  if (($sock = socket_create(AF_INET, SOCK_STREAM, SOL_TCP)) < 0) {    
    echo "Socket creation error";
  }
  else {
    echo "Socket created <br/>";
  }
  if (($ret = socket_bind($sock, $address, $port)) < 0) {
    echo "Host/port connection failed";
  }
  else {
    echo "Host/port connection successful <br/>";
  }
  if (($ret = socket_listen($sock, 5)) < 0) {
    echo "Socket error";
  }
  else {
    echo "Waiting connection <br/>";
  }
 if (($msgsock = socket_accept($sock)) < 0) {
        echo "Socket connection start error";
    } else {
        echo "Awaiting data <br/>";
    }
//Connection established, reading data
    if (false === ($buf = socket_read($msgsock, 1024))) {
        echo "Read error";
    } else {
        echo "Data: ".$buf;
    }
    if (isset($sock)) {
        socket_close($ret);
        socket_close($sock);
    }
    echo "<br /> Socket closed";

To read data from socket dynamically I use jquery request.

Javascript(index.html):

        function update_content() {
            var request = $.get("socket/socketRead.php");
            request.success(function(result) {
                document.write(result);
            });
        }
        update_content();

Worked great until I tried to add interval to read data repeatedly.

Javascript(index.html):

var timer = setInterval(function(){update_content();}, 1000);

The first connection/receiving is still works,but then I get "Connection refused" in C program when trying to connect again. Can you help me with this problem?

Was it helpful?

Solution

You could use SSE for that.

Server Sent Events

https://developer.mozilla.org/en-US/docs/Web/API/EventSource

this does not answer your php question .. but SSE it's made for what you are trying to do.

js

var sse=new EventSource("sse.php");
sse.onmessage=function(e){
 console.log(e.data)
};

sse.php

function send($data){
 echo "id: ".time().PHP_EOL;
 echo "data: ".$data.PHP_EOL;
 echo PHP_EOL;
 ob_flush(); // clear memory
 flush();
}

header('Content-Type: text/event-stream'); // specific sse mimetype
header('Cache-Control: no-cache'); // no cache
$address='localhost';$port=5001;

while(true){
$msg=($sock=socket_create(AF_INET,SOCK_STREAM,SOL_TCP))?'created':'error';
send("Socket creation ".$msg);

$msg=($ret = socket_bind($sock, $address, $port))?'connected':'refused';
send("connection ".$msg);

//.... 
// do the rest  
//.....

sleep(10);
}

note1:Not sure if the php syntax is correct but it's just here to give you an idea.

Another example of sse .. 2nd part is also using json.

https://stackoverflow.com/a/20689738/2450730

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top