Skip to content Skip to sidebar Skip to footer

PHP Receiving Data From TCP Socket Repeatedly

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 o

Solution 1:

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


Post a Comment for "PHP Receiving Data From TCP Socket Repeatedly"