Question
Hello,
I am trying to use your library in my cakephp application. I can successfully connect and disconnect to the node js server but I cannot send the message.
I write the client as in your examples: $socketio = new SocketIO(); if ($socketio->send('localhost', 1337, 'Hello')) { echo 'we sent the message and disconnected'; } else { echo 'Sorry, we have a mistake :'('; }
and for the server: io.sockets.on('connection', function(socket) { console.log('Client connected.');
socket.on('disconnect', function() { console.log('Client disconnected.'); });
socket.on('message', function (msg) { console.log('message from php: ' + msg); })
});
I can see the logs for Client connected and Client disconnected but no messages. Can you see any obvious mistake?
Thank you
Hello! Yes, you have a mistake. when you send a message you need to use "action". Please use this construction:
$socketio->send('localhost', 9090, 'message', 'Hello world!')
I corrected the example in github
Hello, I am trying to use your library in my cakephp application. I can successfully connect and disconnect to the node js server but I cannot send the message. I write the client as in your examples: $socketio = new SocketIO(); if ($socketio->send('localhost', 1337, 'Hello')) { echo 'we sent the message and disconnected'; } else { echo 'Sorry, we have a mistake :'('; } and for the server: io.sockets.on('connection', function(socket) { console.log('Client connected.'); socket.on('disconnect', function() { console.log('Client disconnected.'); }); socket.on('message', function (msg) { console.log('message from php: ' + msg); }) }); I can see the logs for Client connected and Client disconnected but no messages. Can you see any obvious mistake? Thank you — Reply to this email directly or view it on GitHub .
Hello and thanks for your response! I already tried that before and also now by viewing your actual php method. But it's exactly the same result, I can see the connect/disconnect but not the message.
Any other ideas to check?
You can run socketio in DEBUG. For example: DEBUG=* nodejs /path/to/jsscript.js What errors occur when sending a message?
I just figure out that I had to set the environment variable DEBUG=* to view the log.
What I get is: engine handshaking client "LeQXJFsaSeOR2ERaAAAA" +0ms engine:socket sending packet "open" ({"sid":"LeQXJFsaSeOR2ERaAAAA","upgrades":[],"pingInterval":25000,"pingTimeout":60000}) +12ms engine:socket flushing buffer to transport +4ms engine:ws writing "0{"sid":"LeQXJFsaSeOR2ERaAAAA","upgrades":[],"pingInterval":25000,"pingTimeout":60000}" +4ms engine:transport setting request +4ms socket.io:server incoming connection with id LeQXJFsaSeOR2ERaAAAA +9s socket.io:client connecting to namespace / +4ms socket.io:namespace adding socket to nsp / +4ms socket.io:socket socket connected - writing packet +8ms socket.io:socket joining room LeQXJFsaSeOR2ERaAAAA +4ms socket.io:client writing packet {"type":0,"nsp":"/"} +0ms socket.io-parser encoding packet {"type":0,"nsp":"/"} +0ms socket.io-parser encoded {"type":0,"nsp":"/"} as 0 +4ms engine:socket sending packet "message" (0) +32ms engine:socket flushing buffer to transport +4ms engine:ws writing "40" +4ms Client connected. socket.io:socket joined room LeQXJFsaSeOR2ERaAAAA +20ms socket.io:client client close with reason transport close +4ms socket.io:socket closing socket - reason transport close +4ms socket.io:client ignoring remove for LeQXJFsaSeOR2ERaAAAA +4ms Client disconnected.
On 20 April 2015 at 09:42, Fail [email protected] wrote:
You can run socketio in DEBUG. For example: DEBUG=* nodejs /path/to/jsscript.js What errors occur when sending a message?
— Reply to this email directly or view it on GitHub https://github.com/psinetron/PHP_SocketIO_Client/issues/2#issuecomment-94371612 .
You have a transport error. Do you install socket.io server correctly? $out = "GET $address&transport=$transport HTTP/1.1\r\n"; $out.= "Host: http://$host:$port\r\n"; $out.= "Upgrade: WebSocket\r\n"; $out.= "Connection: Upgrade\r\n"; $out.= "Sec-WebSocket-Key: $key\r\n"; $out.= "Sec-WebSocket-Version: 13\r\n"; $out.= "Origin: *\r\n\r\n";
Are you use 'websocket' as transport? Try to set the $key manually. For example ABCD1234
Yes I am using the websocket as transport (I didn't not change anything on your send method)
I have a client side client like this:
and is working fine with log:
socket.io:server incoming connection with id lJ78DYYTFylGSE5QAAAA +17s socket.io:client connecting to namespace / +0ms socket.io:namespace adding socket to nsp / +0ms socket.io:socket socket connected - writing packet +4ms socket.io:socket joining room lJ78DYYTFylGSE5QAAAA +0ms socket.io:client writing packet {"type":0,"nsp":"/"} +4ms Client connected. socket.io:socket joined room lJ78DYYTFylGSE5QAAAA +4ms socket.io:socket got packet {"type":2,"nsp":"/","data":["user message","hello"]} +21s socket.io:socket emitting event ["user message","hello"] +4ms message: hello
Maybe it has something to do with the socket.io version?
Thank you very much for your help!
On 20 April 2015 at 17:25, Fail [email protected] wrote:
You have a transport error. Do you install socket.io server correctly? $out = "GET $address&transport=$transport HTTP/1.1\r\n"; $out.= "Host: http://$host:$port\r\n"; $out.= "Upgrade: WebSocket\r\n"; $out.= "Connection: Upgrade\r\n"; $out.= "Sec-WebSocket-Key: $key\r\n"; $out.= "Sec-WebSocket-Version: 13\r\n"; $out.= "Origin: *\r\n\r\n";
Are you use 'websocket' as transport?
— Reply to this email directly or view it on GitHub https://github.com/psinetron/PHP_SocketIO_Client/issues/2#issuecomment-94466865 .
Yes, exactly the same packages should come from the PHP script. Which version Socket.io do you use?
Node.js version v0.12.0 socket.io version 1.3.5
Thanks!
On 20 April 2015 at 19:05, Fail [email protected] wrote:
Yes, exactly the same packages should come from the PHP script. Which version Socket.io you do you use?
— Reply to this email directly or view it on GitHub https://github.com/psinetron/PHP_SocketIO_Client/issues/2#issuecomment-94494537 .
Yes, it's my mistake. Correct the string $result= fread($fd,1000); to $result= fread($fd,10000); on socket.io.php
And please write that everything is OK ;)
Sorry but not really:) Same as before
Did you made a project example with the latest node js and socket.io and is working fine?
Log: engine handshaking client "ICMoxOY2gX1ZCP0bAAAH" +17s engine:socket sending packet "open" ({"sid":"ICMoxOY2gX1ZCP0bAAAH","upgrades":[],"pingInterval":25000,"pingTimeout":60000}) +16ms engine:socket flushing buffer to transport +0ms engine:ws writing "0{"sid":"ICMoxOY2gX1ZCP0bAAAH","upgrades":[],"pingInterval":25000,"pingTimeout":60000}" +4ms engine:transport setting request +0ms socket.io:server incoming connection with id ICMoxOY2gX1ZCP0bAAAH +3m socket.io:client connecting to namespace / +0ms socket.io:namespace adding socket to nsp / +12ms socket.io:socket socket connected - writing packet +4ms socket.io:socket joining room ICMoxOY2gX1ZCP0bAAAH +0ms socket.io:client writing packet {"type":0,"nsp":"/"} +0ms socket.io-parser encoding packet {"type":0,"nsp":"/"} +2.6m socket.io-parser encoded {"type":0,"nsp":"/"} as 0 +4ms engine:socket sending packet "message" (0) +28ms engine:socket flushing buffer to transport +0ms engine:ws writing "40" +4ms Client connected. socket.io:socket joined room ICMoxOY2gX1ZCP0bAAAH +16ms socket.io:client client close with reason transport close +0ms socket.io:socket closing socket - reason transport close +4ms socket.io:client ignoring remove for ICMoxOY2gX1ZCP0bAAAH +0ms Client disconnected.
Thank you
On 21 April 2015 at 06:18, Fail [email protected] wrote:
Yes, it's my mistake. Correct the string $result= fread($fd,1000); to $result= fread($fd,10000); on socket.io.php
And please write that everything is in order ;)
— Reply to this email directly or view it on GitHub https://github.com/psinetron/PHP_SocketIO_Client/issues/2#issuecomment-94626078 .
Ok. this is my nodejs code:
const websocketport = 9092; //Our port
var io = require('socket.io').listen(websocketport); // Web-socket
io.sockets.on('connection', function (socket) {
console.log("New User connected");
socket.on('message', function (msg) {
console.log("New message: " + msg);
});
socket.on('disconnect', function () {
console.log("User disconnected");
});
});
This is my test PHP code:
<?php
/**
* Class SocketIO
* develope by psinetron (slybeaver)
* Git: https://github.com/psinetron
* web-site: http://slybeaver.ru
*
*/
class SocketIO
{
/**
* @param null $host - $host of socket server
* @param null $port - port of socket server
* @param string $action - action to execute in sockt server
* @param null $data - message to socket server
* @param string $address - addres of socket.io on socket server
* @param string $transport - transport type
* @return bool
*/
public function send($host = null, $port = null, $action= "message", $data = null, $address = "/socket.io/?EIO=2", $transport = 'websocket')
{
$fd = fsockopen($host, $port, $errno, $errstr);
if (!$fd) {
return false;
} //Can't connect tot server
$key = $this->generateKey();
$out = "GET $address&transport=$transport HTTP/1.1\r\n";
$out.= "Host: http://$host:$port\r\n";
$out.= "Upgrade: WebSocket\r\n";
$out.= "Connection: Upgrade\r\n";
$out.= "Sec-WebSocket-Key: $key\r\n";
$out.= "Sec-WebSocket-Version: 13\r\n";
$out.= "Origin: *\r\n\r\n";
fwrite($fd, $out);
// 101 switching protocols, see if echoes key
$result= fread($fd,10000);
preg_match('#Sec-WebSocket-Accept:\s(.*)$#mU', $result, $matches);
$keyAccept = trim($matches[1]);
$expectedResonse = base64_encode(pack('H*', sha1($key . '258EAFA5-E914-47DA-95CA-C5AB0DC85B11')));
$handshaked = ($keyAccept === $expectedResonse) ? true : false;
if ($handshaked){
fwrite($fd, $this->hybi10Encode('42["' . $action . '", "' . addslashes($data) . '"]'));
fread($fd,1000000);
return true;
} else {return false;}
}
private function generateKey($length = 16)
{
$c = 0;
$tmp = '';
while ($c++ * 16 < $length) { $tmp .= md5(mt_rand(), true); }
return base64_encode(substr($tmp, 0, $length));
}
private function hybi10Encode($payload, $type = 'text', $masked = true)
{
$frameHead = array();
$payloadLength = strlen($payload);
switch ($type) {
case 'text':
$frameHead[0] = 129;
break;
case 'close':
$frameHead[0] = 136;
break;
case 'ping':
$frameHead[0] = 137;
break;
case 'pong':
$frameHead[0] = 138;
break;
}
if ($payloadLength > 65535) {
$payloadLengthBin = str_split(sprintf('%064b', $payloadLength), 8);
$frameHead[1] = ($masked === true) ? 255 : 127;
for ($i = 0; $i < 8; $i++) {
$frameHead[$i + 2] = bindec($payloadLengthBin[$i]);
}
if ($frameHead[2] > 127) {
$this->close(1004);
return false;
}
} elseif ($payloadLength > 125) {
$payloadLengthBin = str_split(sprintf('%016b', $payloadLength), 8);
$frameHead[1] = ($masked === true) ? 254 : 126;
$frameHead[2] = bindec($payloadLengthBin[0]);
$frameHead[3] = bindec($payloadLengthBin[1]);
} else {
$frameHead[1] = ($masked === true) ? $payloadLength + 128 : $payloadLength;
}
foreach (array_keys($frameHead) as $i) {
$frameHead[$i] = chr($frameHead[$i]);
}
if ($masked === true) {
$mask = array();
for ($i = 0; $i < 4; $i++) {
$mask[$i] = chr(rand(0, 255));
}
$frameHead = array_merge($frameHead, $mask);
}
$frame = implode('', $frameHead);
for ($i = 0; $i < $payloadLength; $i++) {
$frame .= ($masked === true) ? $payload[$i] ^ $mask[$i % 4] : $payload[$i];
}
return $frame;
}
}
$socketio = new SocketIO();
print 'HI';
if ($socketio->send('XXX.XX.XX.XXX', 9092, 'message', 'Hello world!')){
echo 'we sent the message and disconnected';
} else {
echo 'Sorry, we have a mistake :\'(';
}
?>
This is screenshot of logs:

I use latest socket.io library. Please copy my code, change the IP in php code and verify. I think it'll be work :)
I copied all the code and still did not work. I decided to run node in debug mode and put a breakpoint in the message function like this:
socket.on('message', function (msg) { debugger; console.log('message from php: ' + msg); socket.broadcast.emit('user message', "php user says: ", msg); })
and run: node debug server.js
The strange thing is when I run it like this, and the execution stop at the debugger line it works and I can see the message. That is very strange and I don't know why this is might happening.
I don't want to spend more of your time but if you have any idea about this please let me know.
Thank you for all your help.
On 21 April 2015 at 09:18, Fail [email protected] wrote:
Ok. this is my nodejs code:
const websocketport = 9092; //Our port var io = require('socket.io').listen(websocketport); // Web-Сокет io.sockets.on('connection', function (socket) { console.log("New User connected"); socket.on('message', function (msg) { console.log("New message: " + msg); }); socket.on('disconnect', function () { console.log("User disconnected"); }); });
This is my test PHP code:
generateKey(); $out = "GET $address&transport=$transport HTTP/1.1\r\n"; $out.= "Host: http://$host:$port\r\n"; $out.= "Upgrade: WebSocket\r\n"; $out.= "Connection: Upgrade\r\n"; $out.= "Sec-WebSocket-Key: $key\r\n"; $out.= "Sec-WebSocket-Version: 13\r\n"; $out.= "Origin: *\r\n\r\n"; fwrite($fd, $out); // 101 switching protocols, see if echoes key $result= fread($fd,10000); preg_match('#Sec-WebSocket-Accept:\s(._)$#mU', $result, $matches); $keyAccept = trim($matches[1]); $expectedResonse = base64_encode(pack('H_', sha1($key . '258EAFA5-E914-47DA-95CA-C5AB0DC85B11'))); $handshaked = ($keyAccept === $expectedResonse) ? true : false; if ($handshaked){ fwrite($fd, $this->hybi10Encode('42["' . $action . '", "' . addslashes($data) . '"]')); ``` fread($fd,1000000); return true; ``` } else {return false;} } private function generateKey($length = 16) { $c = 0; $tmp = ''; while ($c++ \* 16 65535) { $payloadLengthBin = str_split(sprintf('%064b', $payloadLength), 8); $frameHead[1] = ($masked === true) ? 255 : 127; for ($i = 0; $i 127) { $this->close(1004); return false; } } elseif ($payloadLength > 125) { $payloadLengthBin = str_split(sprintf('%016b', $payloadLength), 8); $frameHead[1] = ($masked === true) ? 254 : 126; $frameHead[2] = bindec($payloadLengthBin[0]); $frameHead[3] = bindec($payloadLengthBin[1]); } else { $frameHead[1] = ($masked === true) ? $payloadLength + 128 : $payloadLength; } foreach (array_keys($frameHead) as $i) { $frameHead[$i] = chr($frameHead[$i]); } if ($masked === true) { $mask = array(); for ($i = 0; $i send('XXX.XX.XX.XXX', 9092, 'message', 'Hello world!')){ echo 'we sent the message and disconnected'; } else { echo 'Sorry, we have a mistake :\'('; } ?>This is screenshot of logs: [image: screenshot_3] https://cloud.githubusercontent.com/assets/3624600/7246489/3f2d8c90-e820-11e4-8eb4-e0b61011878d.png
I use latest socket.io library. Please copy my code, change the IP in php code and verify. I think it'll be work :)
— Reply to this email directly or view it on GitHub https://github.com/psinetron/PHP_SocketIO_Client/issues/2#issuecomment-94652287 .
It's so strange. Probably too fast PHP attempts to connect and send the message. Try inserting sleep in PHP code to send messages took place some time after the connection
I did added a sleep for 2 seconds before the fwrite message and it's working. But I am not sure If I feel confident to work every time.
I appreciate your work and effort you gave into this.
Thank you again!
On 21 April 2015 at 11:49, Fail [email protected] wrote:
It's so strange. Probably too fast PHP attempts to connect and send the message. Try inserting sleep in PHP code to send messages took place some time after the connection
— Reply to this email directly or view it on GitHub https://github.com/psinetron/PHP_SocketIO_Client/issues/2#issuecomment-94707156 .
You need to read up until while you meet "Sec-WebSocket-Protocol: websocket"
I think it would be a good. I use this code in my Java projects
Can you explain more what do you mean with:
You need to read up until while you meet "Sec-WebSocket-Protocol: websocket"
I used it on Windows Azure and after I remove the http:// from this line it worked: $out.= "Host: http://$host:$port\r\n";
When you receive a reply from the server, you need to keep track of the line Sec-WebSocket-Protocol: websocket. Only then you can send your message
Hi, Thanks for your example, I tried the send message function and it works. there is any function built as send function, to read socket io data ?
I tried this, but it not working :
`public function read($host = null, $port = null, $action= "message", $data = null, $address = "/socket.io/?EIO=2", $transport = 'websocket') { $fd = fsockopen($host, $port, $errno, $errstr); if (!$fd) { return false; } //Can't connect to the server $key = $this->generateKey();
$out = "GET $address&transport=$transport HTTP/1.1\r\n";
$out.= "Host: http://$host:$port\r\n";
$out.= "Upgrade: WebSocket\r\n";
$out.= "Connection: Upgrade\r\n";
$out.= "Sec-WebSocket-Key: $key\r\n";
$out.= "Sec-WebSocket-Version: 13\r\n";
$out.= "Origin: *\r\n\r\n";
fwrite($fd, $out);
// 101 switching protocols, see if echoes key
$result= fread($fd,10000);
echo '****'.$result.'****';
}`
I'm using latest node.js and socket.io but I faced the same issue as this topic. Is there a fix for this?
Thanks.
@psinetron , Your snippet worked like a charm!
This is my socket.io server code: var app = require('express')(); var http = require('http').Server(app); var io = require('socket.io')(http); var cors = require('cors');
app.use(cors());
app.get('/', function(req, res){ res.sendFile(__dirname + '/index.html'); });
io.sockets.on('connection', function(socket){ console.log('1 client connected');
socket.on('message', function(msg){ console.log('message: ' + msg); });
socket.on('disconnect', function(){ console.log('1 client disconnected'); }); });
http.listen(3000, function(){ console.log('listening on *:3000'); });
Thanks.