Skip to content

Instantly share code, notes, and snippets.

@nxvhm
Created March 2, 2019 18:34
Show Gist options
  • Select an option

  • Save nxvhm/72aafdf47b3c0c59605857658826b0cb to your computer and use it in GitHub Desktop.

Select an option

Save nxvhm/72aafdf47b3c0c59605857658826b0cb to your computer and use it in GitHub Desktop.
PHP to SocketIO or any WAMP Socket Server
<?php
# Note that 8080 is the port to my Node.js server - you may want to change.
function sio_message($message, $data) {
$socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
$result = socket_connect($socket, '127.0.0.1', 8080);
if(!$result) {
die('cannot connect '.socket_strerror(socket_last_error()).PHP_EOL);
}
$bytes = socket_write($socket, json_encode(Array("msg" => $message, "data" => $data)));
socket_close($socket);
}
//You might have something like this - just included to show object setup
var app = express();
var server = http.createServer(app);
var io = require('socket.io').listen(server);
server.on("connection", function(s) {
//If connection is from our server (localhost)
if(s.remoteAddress == "::ffff:127.0.0.1") {
s.on('data', function(buf) {
var js = JSON.parse(buf);
io.emit(js.msg,js.data); //Send the msg to socket.io clients
});
}
});
You can use it like this:
sio_message("chat message","Hello from PHP!");
You can also send arrays which are converted to json and passed along to clients.
sio_message("DataUpdate",Array("Data1" => "something", "Data2" => "something else"));
This is a useful way to "trust" that your clients are getting legitimate messages from the server.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment