everyone
I'm a new learner with websocket.
I want to deploy my websocket server on GCE.
However, I got some problem.
environment:
Backend:server.php(use php socket function) run on 8080 port
fronend:client.html(simple javascript)
GCE: Ubuntu 18.04, PHP 7.3, apache 2.4.29
without any google cloud sdk (only 2 program and 1 GCE instance)
problem:
Server can work well at my local machine (windows 10), but on GCE websocket will show "1006" error code.
There is a interesting thing that is client.html can work on GCE when I run server.php at local machine.
Is it normal? What is the connection with my local machine and GCE.
Maybe it's not a firewall blocking problem.
I wonder my websocket doesn't run because of the firewall port blocking at first.
I have set the VPC firewall rule with following GCP document and I also disable ufw on GCE.
I change the apache's port from 80 to 8080 and run apache.
It works successfully and I check netstat -an | grep "LISTEN "
I use telnet GCE_IP 8080 at my local machine but it can't connect.
Here is my code:
server.php
<?php
error_reporting(E_ALL);
set_time_limit(0);
class WebSocket {
const LOG_PATH = '/tmp/';
const LISTEN_SOCKET_NUM = 9;
private $sockets = [];
private $master;
public function __construct($host, $port) {
try {
$this->master = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
socket_set_option($this->master, SOL_SOCKET, SO_REUSEADDR, 1);
socket_bind($this->master, $host, $port);
socket_listen($this->master, self::LISTEN_SOCKET_NUM);
} catch (\Exception $e) {
$err_code = socket_last_error();
$err_msg = socket_strerror($err_code);
}
$this->sockets[0] = ['resource' => $this->master];
$pid = posix_getpid();
while (true) {
try {
$this->doServer();
} catch (\Exception $e) {
}
}
}
private function doServer() {
$write = $except = NULL;
$sockets = array_column($this->sockets, 'resource');
$read_num = socket_select($sockets, $write, $except, NULL);
if (false === $read_num) {
return;
}
foreach ($sockets as $socket) {
if ($socket == $this->master) {
$client = socket_accept($this->master);
if (false === $client) {
continue;
} else {
self::connect($client);
continue;
}
} else {
$bytes = #socket_recv($socket, $buffer, 2048, 0);
if ($bytes < 9) {
$recv_msg = $this->disconnect($socket);
} else {
if (!$this->sockets[(int)$socket]['handshake']) {
self::handShake($socket, $buffer);
continue;
} else {
$recv_msg = self::parse($buffer);
}
}
array_unshift($recv_msg, 'receive_msg');
$msg = self::dealMsg($socket, $recv_msg);
$this->broadcast($msg);
}
}
}
public function connect($socket) {
socket_getpeername($socket, $ip, $port);
$socket_info = [
'resource' => $socket,
'uname' => '',
'handshake' => false,
'ip' => $ip,
'port' => $port,
];
$this->sockets[(int)$socket] = $socket_info;
}
private function disconnect($socket) {
$recv_msg = [
'type' => 'logout',
'content' => $this->sockets[(int)$socket]['uname'],
];
unset($this->sockets[(int)$socket]);
return $recv_msg;
}
public function handShake($socket, $buffer) {
$line_with_key = substr($buffer, strpos($buffer, 'Sec-WebSocket-Key:') + 18);
$key = trim(substr($line_with_key, 0, strpos($line_with_key, "\r\n")));
$upgrade_key = base64_encode(sha1($key . "258EAFA5-E914-47DA-95CA-C5AB0DC85B11", true));
$upgrade_message = "HTTP/1.1 101 Switching Protocols\r\n";
$upgrade_message .= "Upgrade: websocket\r\n";
$upgrade_message .= "Sec-WebSocket-Version: 13\r\n";
$upgrade_message .= "Connection: Upgrade\r\n";
$upgrade_message .= "Sec-WebSocket-Accept:" . $upgrade_key . "\r\n\r\n";
socket_write($socket, $upgrade_message, strlen($upgrade_message));
$this->sockets[(int)$socket]['handshake'] = true;
socket_getpeername($socket, $ip, $port);
$msg = [
'type' => 'handshake',
'content' => 'done',
];
$msg = $this->build(json_encode($msg));
socket_write($socket, $msg, strlen($msg));
return true;
}
private function parse($buffer) {
$decoded = '';
$len = ord($buffer[1]) & 127;
if ($len === 126) {
$masks = substr($buffer, 4, 4);
$data = substr($buffer, 8);
} else if ($len === 127) {
$masks = substr($buffer, 10, 4);
$data = substr($buffer, 14);
} else {
$masks = substr($buffer, 2, 4);
$data = substr($buffer, 6);
}
for ($index = 0; $index < strlen($data); $index++) {
$decoded .= $data[$index] ^ $masks[$index % 4];
}
return json_decode($decoded, true);
}
private function build($msg) {
$frame = [];
$frame[0] = '81';
$len = strlen($msg);
if ($len < 126) {
$frame[1] = $len < 16 ? '0' . dechex($len) : dechex($len);
} else if ($len < 65025) {
$s = dechex($len);
$frame[1] = '7e' . str_repeat('0', 4 - strlen($s)) . $s;
} else {
$s = dechex($len);
$frame[1] = '7f' . str_repeat('0', 16 - strlen($s)) . $s;
}
$data = '';
$l = strlen($msg);
for ($i = 0; $i < $l; $i++) {
$data .= dechex(ord($msg{$i}));
}
$frame[2] = $data;
$data = implode('', $frame);
return pack("H*", $data);
}
private function dealMsg($socket, $recv_msg) {
$msg_type = $recv_msg['type'];
$msg_content = $recv_msg['content'];
$response = [];
switch ($msg_type) {
case 'login':
$this->sockets[(int)$socket]['uname'] = $msg_content;
$user_list = array_column($this->sockets, 'uname');
$response['type'] = 'login';
$response['content'] = $msg_content;
$response['user_list'] = $user_list;
break;
case 'logout':
$user_list = array_column($this->sockets, 'uname');
$response['type'] = 'logout';
$response['content'] = $msg_content;
$response['user_list'] = $user_list;
break;
case 'user':
$uname = $this->sockets[(int)$socket]['uname'];
$response['type'] = 'user';
$response['from'] = $uname;
$response['content'] = $msg_content;
break;
}
return $this->build(json_encode($response));
}
private function broadcast($data) {
foreach ($this->sockets as $socket) {
if ($socket['resource'] == $this->master) {
continue;
}
socket_write($socket['resource'], $data, strlen($data));
}
}
}
$ws = new WebSocket("localhost", "8080");
client.html
<html>
<head>
<title></title>
<meta http-equiv="content-type" content="text/html;charset=utf-8">
<style>
p {
text-align: left;
padding-left: 20px;
}
</style>
</head>
<body>
<div style="width: 800px;height: 600px;margin: 30px auto;text-align: center">
<h1>chat room</h1>
<div style="width: 800px;border: 1px solid gray;height: 300px;">
<div style="width: 200px;height: 300px;float: left;text-align: left;">
<p><span>online:</span><span id="user_num">0</span></p>
<div id="user_list" style="overflow: auto;">
</div>
</div>
<div id="msg_list" style="width: 598px;border: 1px solid gray; height: 300px;overflow: scroll;float: left;">
</div>
</div>
<br>
<textarea id="msg_box" rows="6" cols="50" onkeydown="confirm(event)"></textarea><br>
<input type="button" value="send" onclick="send()">
</div>
</body>
</html>
<script type="text/javascript">
var uname = prompt('type your name', 'user');
var ws = new WebSocket("ws://127.0.0.1:8080");
ws.onopen = function () {
var data = "system:connect successfully";
listMsg(data);
};
ws.onmessage = function (e) {
var msg = JSON.parse(e.data);
var sender, user_name, name_list, change_type;
switch (msg.type) {
case 'system':
sender = 'system: ';
break;
case 'user':
sender = msg.from + ': ';
break;
case 'handshake':
var user_info = {'type': 'login', 'content': uname};
sendMsg(user_info);
return;
case 'login':
case 'logout':
user_name = msg.content;
name_list = msg.user_list;
change_type = msg.type;
dealUser(user_name, change_type, name_list);
return;
}
var data = sender + msg.content;
listMsg(data);
};
ws.onerror = function () {
var data = "system : something wrong";
listMsg(data);
};
function confirm(event) {
var key_num = event.keyCode;
if (13 == key_num) {
send();
} else {
return false;
}
}
function send() {
var msg_box = document.getElementById("msg_box");
var content = msg_box.value;
var reg = new RegExp("\r\n", "g");
content = content.replace(reg, "");
var msg = {'content': content.trim(), 'type': 'user'};
sendMsg(msg);
msg_box.value = '';
}
function listMsg(data) {
var msg_list = document.getElementById("msg_list");
var msg = document.createElement("p");
msg.innerHTML = data;
msg_list.appendChild(msg);
msg_list.scrollTop = msg_list.scrollHeight;
}
function dealUser(user_name, type, name_list) {
var user_list = document.getElementById("user_list");
var user_num = document.getElementById("user_num");
while(user_list.hasChildNodes()) {
user_list.removeChild(user_list.firstChild);
}
for (var index in name_list) {
var user = document.createElement("p");
user.innerHTML = name_list[index];
user_list.appendChild(user);
}
user_num.innerHTML = name_list.length;
user_list.scrollTop = user_list.scrollHeight;
var change = type == 'login' ? 'online' : 'offline';
var data = 'system:' + user_name + ' is' + change;
listMsg(data);
}
function sendMsg(msg) {
var data = JSON.stringify(msg);
ws.send(data);
}
</script>
on GCE VM:
update
internal IP: .3
external IP: .62
1.
netstat -an | grep "LISTEN " to check if you configured internal IP instead of localhost or/and 127.0.0.1
.
I change my internal IP in the server.php and run.
It looks like working perfectly.
2.
Connection check from the GCE VM to GCE_VM_INTERNAL_IP:8080.
.
Connect successfully!
3.
Connection check from you personal computer to
GCE_VM_EXTERNAL_IP:8080. Also, consider to use curl instead of
telnet
.
It seems that handshaking can work.
I can get websocket message from GCE with internal IP and PC with external IP.
So my problem is maybe like in javascript?
It doesn't send the handshaking frame.
Related
I have used WebSocket in PHP. but somehow it will close after some time(so many requests).
Is it anyway to handle it?
We got following error when we try to run it after stop:
socket_bind(): unable to bind address [10013]: An attempt was made to
access a socket in a way forbidden by its access permissions.
in C:\wamp64\www\Websocket\server.php on line 52
Warning: socket_listen(): unable to listen on socket [10022]: An invalid argument was supplied.
in C:\wamp64\www\Websocket\server.php on line 55
Here is my code:
<?php
set_time_limit(0);
error_reporting(E_ALL);
//include 'Triangulate.php';
$filename = 'logs.txt';
class Values
{
public $distance;
public $rasp_id;
public $rssi;
}
$host = '10.37.54.167'; //host
$port = '9000'; //port
$null = null; //null var
$rasp = array(
47 => array(17, 0),
124 => array(1,6.4),
43 => array(1,0),
44 => array(4.6,2));
//Create TCP/IP sream socket
$socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
//reuseable port
socket_set_option($socket, SOL_SOCKET, SO_REUSEADDR, 1);
//bind socket to specified host
socket_bind($socket, 0, $port);
//listen to port
socket_listen($socket);
//create & add listning socket to the list
$clients = array($socket);
$distance = array();
$totalbicken = array(array());
//start endless loop, so that our script doesn't stop
while (true) {
//manage multipal connections
$changed = $clients;
//returns the socket resources in $changed array
socket_select($changed, $null, $null, 0, 10);
$fp = fopen($filename, 'a+');
//check for new socket
if (in_array($socket, $changed)) {
$socket_new = socket_accept($socket); //accpet new socket
$clients[] = $socket_new; //add socket to client array
$header = socket_read($socket_new, 1024); //read data sent by the socket
perform_handshaking($header, $socket_new, $host, $port); //perform websocket handshake
socket_getpeername($socket_new, $ip); //get ip address of connected socket
$response = mask(json_encode(array('type' => 'system', 'message' => $ip . ' connected'))); //prepare json data
fwrite ($fp,$response . "\n");
// send_message($response); //notify all users about new connection
// send_message_socket($response, $socket_new);
//make room for new socket
$found_socket = array_search($socket, $changed);
unset($changed[$found_socket]);
}
//loop through all connected sockets
foreach ($changed as $changed_socket) {
//check for any incomming data
try {
while (socket_recv($changed_socket, $buf, 1024, 0) >= 1) {
$received_text = unmask($buf); //Unmask Recive data.
fwrite ($fp,"Text receive:" . $received_text . "\n");
$tst_msg = json_decode($received_text); //json decode.
fwrite ($fp,"Json Decord!". "\n");
if (!isset($tst_msg->action)) {
} else {
$user_action = $tst_msg->action; //sender name.
if ($user_action == "distance") { //If action is distance.
$rasp_id = $tst_msg->rasp_id; //get raspberry uniq id.
$beacon_id = $tst_msg->beacon_id; //get beacon id
$distance_temp = $tst_msg->distance; // get distance
$rssi = $tst_msg->rssi; //get RSSI.
fwrite ($fp,isset($distance[$beacon_id]). "\n");
fwrite ($fp,"Get all values!". "\n");
// echo mask(json_encode(array('type'=>'message', 'action'=>'distance', 'beacon_id'=>$beacon_id, 'rasp_id'=>$rasp_id, 'distance'=>$distance)));
if (isset($distance[$beacon_id])) {
$totalbicken[$beacon_id] = count($distance[$beacon_id]); //get total distance of sender beacon
} else {
$totalbicken[$beacon_id] = 0;
}
if (isset($rasp[$rasp_id])) {
echo "\nRequest from: " . $rasp_id;
$myVal = new Values();
$myVal->distance = $distance_temp;
$myVal->rasp_id = $rasp_id;
$myVal->rssi = $rssi;
$flag = false;
if (isset($distance[$beacon_id])) {
if (count($distance[$beacon_id]) > 0) {
for ($i = 0; $i < count($distance[$beacon_id]); $i++) {
$myTempVal = $distance[$beacon_id][$i];
if (($myTempVal->rasp_id) == $rasp_id) {
$flag = true;
$distance[$beacon_id][$i] = $myVal;
break;
}
}
if (!$flag) {
$distance[$beacon_id][$totalbicken[$beacon_id]] = $myVal;
}
} else {
$distance[$beacon_id][$totalbicken[$beacon_id]] = $myVal;
}
} else {
$distance[$beacon_id][$totalbicken[$beacon_id]] = $myVal;
}
if (count($distance[$beacon_id]) > 2) {
/*$data = triangulate($rasp[$distance[$beacon_id][0]->rasp_id], $distance[$beacon_id][0]->distance,
$rasp[$distance[$beacon_id][1]->rasp_id], $distance[$beacon_id][1]->distance,
$rasp[$distance[$beacon_id][2]->rasp_id], $distance[$beacon_id][2]->distance);*/
fwrite ($fp,"Before Triangulation!". "\n");
$data = getTrilateration($rasp[$distance[$beacon_id][0]->rasp_id], $distance[$beacon_id][0]->distance,
$rasp[$distance[$beacon_id][1]->rasp_id], $distance[$beacon_id][1]->distance,
$rasp[$distance[$beacon_id][2]->rasp_id], $distance[$beacon_id][2]->distance);
fwrite ($fp,"End Triangulation!". "\n");
$response_text = mask(json_encode(array('type' => 'message', 'action' => 'distance',
'beacon_id' => $beacon_id, 'distance' => $distance[$beacon_id], 'coordinates' => $data)));
fwrite ($fp,"Response: ". $response_text . "\n");
send_message($response_text);
}
}
}
fwrite ($fp,"Break!: ". "\n");
break 2; //exist this loop*/
}
}
} catch (Exception $e) {
fwrite ($fp,"Exception: done! \n");
fwrite ($fp,"Exception: ". $e->getMessage(). "\n");
echo "Exception:" . $e->getMessage();
}
$buf = #socket_read($changed_socket, 1024, PHP_NORMAL_READ);
if ($buf === false) { // check disconnected client
// remove client for $clients array
try {
$found_socket = array_search($changed_socket, $clients);
socket_getpeername($changed_socket, $ip);
unset($clients[$found_socket]);
//notify all users about disconnected connection
$response = mask(json_encode(array('type' => 'system', 'message' => $ip . ' disconnected')));
send_message($response);
} catch (Exception $e) {
echo "Exception:" . $e;
}
}
}
}
// close the listening socket
socket_close($socket);
$fclose ($fp);
function send_message($msg)
{
global $clients;
foreach ($clients as $changed_socket) {
#socket_write($changed_socket, $msg, strlen($msg));
}
return true;
}
function send_message_socket($msg, $changed_socket)
{
#socket_write($changed_socket, $msg, strlen($msg));
return true;
}
//Unmask incoming framed message
function unmask($text)
{
$length = ord($text[1]) & 127;
if ($length == 126) {
$masks = substr($text, 4, 4);
$data = substr($text, 8);
} elseif ($length == 127) {
$masks = substr($text, 10, 4);
$data = substr($text, 14);
} else {
$masks = substr($text, 2, 4);
$data = substr($text, 6);
}
$text = "";
for ($i = 0; $i < strlen($data); ++$i) {
$text .= $data[$i] ^ $masks[$i % 4];
}
return $text;
}
//Encode message for transfer to client.
function mask($text)
{
$b1 = 0x80 | (0x1 & 0x0f);
$length = strlen($text);
if ($length <= 125) {
$header = pack('CC', $b1, $length);
} elseif ($length > 125 && $length < 65536) {
$header = pack('CCn', $b1, 126, $length);
} elseif ($length >= 65536) {
$header = pack('CCNN', $b1, 127, $length);
}
return $header . $text;
}
//handshake new client.
function perform_handshaking($receved_header, $client_conn, $host, $port)
{
$headers = array();
$lines = preg_split("/\r\n/", $receved_header);
foreach ($lines as $line) {
$line = chop($line);
if (preg_match('/\A(\S+): (.*)\z/', $line, $matches)) {
$headers[$matches[1]] = $matches[2];
}
}
$secKey = $headers['Sec-WebSocket-Key'];
$secAccept = base64_encode(pack('H*', sha1($secKey . '258EAFA5-E914-47DA-95CA-C5AB0DC85B11')));
//hand shaking header
$upgrade = "HTTP/1.1 101 Web Socket Protocol Handshake\r\n" .
"Upgrade: websocket\r\n" .
"Connection: Upgrade\r\n" .
"WebSocket-Origin: $host\r\n" .
"WebSocket-Location: ws://$host:$port/Websocket/shout.php\r\n" .
"Sec-WebSocket-Accept:$secAccept\r\n\r\n";
socket_write($client_conn, $upgrade, strlen($upgrade));
}
Thanks in advance!
I have setup Linux environment and test. It is working fine. It might a firewall issue in windows.
As per my knowledge, the newer version of windows (after service pack-3) has some of the RPC rules for connection (Limit of HTTP requests and connection in second) so, that might be an issue.
Please read this.
As of now, change the operating system is the one of a solution.
Thanks & Regards
Jignesh M. Mehta
I have following code
index.php
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<style type="text/css">
.panel{
margin-right: 3px;
}
.button {
background-color: #4CAF50;
border: none;
color: white;
margin-right: 30%;
margin-left: 30%;
text-decoration: none;
display: block;
font-size: 16px;
cursor: pointer;
width:30%;
height:40px;
margin-top: 5px;
}
input[type=text]{
width:100%;
margin-top:5px;
}
.chat_wrapper {
width: 70%;
height:472px;
margin-right: auto;
margin-left: auto;
background: #3B5998;
border: 1px solid #999999;
padding: 10px;
font: 14px 'lucida grande',tahoma,verdana,arial,sans-serif;
}
.chat_wrapper .message_box {
background: #F7F7F7;
height:350px;
overflow: auto;
padding: 10px 10px 20px 10px;
border: 1px solid #999999;
}
.chat_wrapper input{
//padding: 2px 2px 2px 5px;
}
.system_msg{color: #BDBDBD;font-style: italic;}
.user_name{font-weight:bold;}
.user_message{color: #88B6E0;}
#media only screen and (max-width: 720px) {
/* For mobile phones: */
.chat_wrapper {
width: 95%;
height: 40%;
}
.button{ width:100%;
margin-right:auto;
margin-left:auto;
height:40px;}
}
</style>
</head>
<body>
<?php
$colours = array('007AFF','FF7000','FF7000','15E25F','CFC700','CFC700','CF1100','CF00BE','F00');
$user_colour = array_rand($colours);
?>
<script src="jquery-3.1.1.js"></script>
<script language="javascript" type="text/javascript">
$(document).ready(function(){
//create a new WebSocket object.
var wsUri = "ws://localhost:9000/demo/server.php";
websocket = new WebSocket(wsUri);
websocket.onopen = function(ev) { // connection is open
$('#message_box').append("<div class=\"system_msg\">Connected!</div>"); //notify user
}
$('#send-btn').click(function(){ //use clicks message send button
var mymessage = $('#message').val(); //get message text
var myname = $('#name').val(); //get user name
if(myname == ""){ //empty name?
alert("Enter your Name please!");
return;
}
if(mymessage == ""){ //emtpy message?
alert("Enter Some message Please!");
return;
}
document.getElementById("name").style.visibility = "hidden";
var objDiv = document.getElementById("message_box");
objDiv.scrollTop = objDiv.scrollHeight;
//prepare json data
var msg = {
message: mymessage,
name: myname,
color : '<?php echo $colours[$user_colour]; ?>'
};
//convert and send data to server
websocket.send(JSON.stringify(msg));
});
//#### Message received from server?
websocket.onmessage = function(ev) {
var msg = JSON.parse(ev.data); //PHP sends Json data
var type = msg.type; //message type
var umsg = msg.message; //message text
var uname = msg.name; //user name
var ucolor = msg.color; //color
if(type == 'usermsg')
{
$('#message_box').append("<div><span class=\"user_name\" style=\"color:#"+ucolor+"\">"+uname+"</span> : <span class=\"user_message\">"+umsg+"</span></div>");
}
if(type == 'system')
{
$('#message_box').append("<div class=\"system_msg\">"+umsg+"</div>");
}
$('#message').val(''); //reset text
var objDiv = document.getElementById("message_box");
objDiv.scrollTop = objDiv.scrollHeight;
};
websocket.onerror = function(ev){$('#message_box').append("<div class=\"system_error\">Error Occurred - "+ev.data+"</div>");};
websocket.onclose = function(ev){$('#message_box').append("<div class=\"system_msg\">Connection Closed</div>");};
});
</script>
<div class="chat_wrapper">
<div class="message_box" id="message_box"></div>
<div class="panel">
<input type="text" name="name" id="name" placeholder="Your Name" maxlength="15" />
<input type="text" name="message" id="message" placeholder="Message" maxlength="80"
onkeydown = "if (event.keyCode == 13)document.getElementById('send-btn').click()" />
</div>
<button id="send-btn" class=button>Send</button>
</div>
</body>
</html>
server.php
<?php
$host = 'localhost'; //host
$port = '9000'; //port
$null = NULL; //null var
//Create TCP/IP sream socket
$socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
//reuseable port
socket_set_option($socket, SOL_SOCKET, SO_REUSEADDR, 1);
//bind socket to specified host
socket_bind($socket, 0, $port);
//listen to port
socket_listen($socket);
//create & add listning socket to the list
$clients = array($socket);
//start endless loop, so that our script doesn't stop
while (true) {
//manage multipal connections
$changed = $clients;
//returns the socket resources in $changed array
socket_select($changed, $null, $null, 0, 10);
//check for new socket
if (in_array($socket, $changed)) {
$socket_new = socket_accept($socket); //accpet new socket
$clients[] = $socket_new; //add socket to client array
$header = socket_read($socket_new, 1024); //read data sent by the socket
perform_handshaking($header, $socket_new, $host, $port); //perform websocket handshake
socket_getpeername($socket_new, $ip); //get ip address of connected socket
$response = mask(json_encode(array('type'=>'system', 'message'=>$ip.' connected'))); //prepare json data
send_message($response); //notify all users about new connection
//make room for new socket
$found_socket = array_search($socket, $changed);
unset($changed[$found_socket]);
}
//loop through all connected sockets
foreach ($changed as $changed_socket) {
//check for any incomming data
while(socket_recv($changed_socket, $buf, 1024, 0) >= 1)
{
$received_text = unmask($buf); //unmask data
$tst_msg = json_decode($received_text); //json decode
$user_name = $tst_msg->name; //sender name
$user_message = $tst_msg->message; //message text
$user_color = $tst_msg->color; //color
//prepare data to be sent to client
$response_text = mask(json_encode(array('type'=>'usermsg', 'name'=>$user_name, 'message'=>$user_message, 'color'=>$user_color)));
send_message($response_text); //send data
break 2; //exist this loop
}
$buf = #socket_read($changed_socket, 1024, PHP_NORMAL_READ);
if ($buf === false) { // check disconnected client
// remove client for $clients array
$found_socket = array_search($changed_socket, $clients);
socket_getpeername($changed_socket, $ip);
unset($clients[$found_socket]);
//notify all users about disconnected connection
$response = mask(json_encode(array('type'=>'system', 'message'=>$ip.' disconnected')));
send_message($response);
}
}
}
// close the listening socket
socket_close($socket);
function send_message($msg)
{
global $clients;
foreach($clients as $changed_socket)
{
#socket_write($changed_socket,$msg,strlen($msg));
}
return true;
}
//Unmask incoming framed message
function unmask($text) {
$length = ord($text[1]) & 127;
if($length == 126) {
$masks = substr($text, 4, 4);
$data = substr($text, 8);
}
elseif($length == 127) {
$masks = substr($text, 10, 4);
$data = substr($text, 14);
}
else {
$masks = substr($text, 2, 4);
$data = substr($text, 6);
}
$text = "";
for ($i = 0; $i < strlen($data); ++$i) {
$text .= $data[$i] ^ $masks[$i%4];
}
return $text;
}
//Encode message for transfer to client.
function mask($text)
{
$b1 = 0x80 | (0x1 & 0x0f);
$length = strlen($text);
if($length <= 125)
$header = pack('CC', $b1, $length);
elseif($length > 125 && $length < 65536)
$header = pack('CCn', $b1, 126, $length);
elseif($length >= 65536)
$header = pack('CCNN', $b1, 127, $length);
return $header.$text;
}
//handshake new client.
function perform_handshaking($receved_header,$client_conn, $host, $port)
{
$headers = array();
$lines = preg_split("/\r\n/", $receved_header);
foreach($lines as $line)
{
$line = chop($line);
if(preg_match('/\A(\S+): (.*)\z/', $line, $matches))
{
$headers[$matches[1]] = $matches[2];
}
}
$secKey = $headers['Sec-WebSocket-Key'];
$secAccept = base64_encode(pack('H*', sha1($secKey . '258EAFA5-E914-47DA-95CA-C5AB0DC85B11')));
//hand shaking header
$upgrade = "HTTP/1.1 101 Web Socket Protocol Handshake\r\n" .
"Upgrade: websocket\r\n" .
"Connection: Upgrade\r\n" .
"WebSocket-Origin: $host\r\n" .
"WebSocket-Location: ws://$host:$port/demo/shout.php\r\n".
"Sec-WebSocket-Accept:$secAccept\r\n\r\n";
socket_write($client_conn,$upgrade,strlen($upgrade));
}
The above code is working fine.But now i am looking for client side as php .can any provide me some example to make client websocket using php
UPDATES
I need to send byte array using php or javascript library through websocket
Update 2
I have found simple class of websocket but dont know how to use
https://github.com/paragi/PHP-websocket-client/blob/master/websocket_client.php
Also as per Niket Pathak answer i tried but getting following error
<?php
$host = 'ws://echo.websocket.org'; // your websocket server
$port = 80;
$local = "http://localhost"; // url where this script run | Client
$data = '{"id": 2,"command": "server_info"}'; // data to be sent
$head = "GET / HTTP/1.1"."\r\n".
"Upgrade: WebSocket"."\r\n".
"Connection: Upgrade"."\r\n".
"Origin: $local"."\r\n".
"Host: $host"."\r\n".
"Sec-WebSocket-Version: 13"."\r\n".
"Sec-WebSocket-Key: asdasdaas76da7sd6asd6as7d"."\r\n".
"Content-Length: ".strlen($data)."\r\n"."\r\n";
// WebSocket handshake
$sock = fsockopen($host, $port, $errno, $errstr, 2);
fwrite($sock, $head ) or die('error:'.$errno.':'.$errstr);
$headers = fread($sock, 2000);
fwrite($sock, hybi10Encode($data)) or die('error:'.$errno.':'.$errstr);
$wsdata = fread($sock, 2000);
fclose($sock);
var_dump(hybi10Decode($wsdata));
// hibi10 decoding of data
function hybi10Decode($data)
{
$bytes = $data;
$dataLength = '';
$mask = '';
$coded_data = '';
$decodedData = '';
$secondByte = sprintf('%08b', ord($bytes[1]));
$masked = ($secondByte[0] == '1') ? true : false;
$dataLength = ($masked === true) ? ord($bytes[1]) & 127 : ord($bytes[1]);
if($masked === true)
{
if ($dataLength === 126) {
$mask = substr($bytes, 4, 4);
$coded_data = substr($bytes, 8);
}
elseif ($dataLength === 127) {
$mask = substr($bytes, 10, 4);
$coded_data = substr($bytes, 14);
}
else {
$mask = substr($bytes, 2, 4);
$coded_data = substr($bytes, 6);
}
for ($i = 0; $i < strlen($coded_data); $i++) {
$decodedData .= $coded_data[$i] ^ $mask[$i % 4];
}
}
else {
if ($dataLength === 126) {
$decodedData = substr($bytes, 4);
}
elseif ($dataLength === 127) {
$decodedData = substr($bytes, 10);
}
else {
$decodedData = substr($bytes, 2);
}
}
return $decodedData;
}
// hibi10 encoding of data
function hybi10Encode($payload, $type = 'text', $masked = true) {
$frameHead = array();
$frame = '';
$payloadLength = strlen($payload);
switch ($type) {
case 'text':
// first byte indicates FIN, Text-Frame (10000001):
$frameHead[0] = 129;
break;
case 'close':
// first byte indicates FIN, Close Frame(10001000):
$frameHead[0] = 136;
break;
case 'ping':
// first byte indicates FIN, Ping frame (10001001):
$frameHead[0] = 137;
break;
case 'pong':
// first byte indicates FIN, Pong frame (10001010):
$frameHead[0] = 138;
break;
}
// set mask and payload length (using 1, 3 or 9 bytes)
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]);
}
// most significant bit MUST be 0 (close connection if frame too big)
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;
}
// convert frame-head to string:
foreach (array_keys($frameHead) as $i) {
$frameHead[$i] = chr($frameHead[$i]);
}
if ($masked === true) {
// generate a random mask:
$mask = array();
for ($i = 0; $i < 4; $i++) {
$mask[$i] = chr(rand(0, 255));
}
$frameHead = array_merge($frameHead, $mask);
}
$frame = implode('', $frameHead);
// append payload to frame:
for ($i = 0; $i < $payloadLength; $i++) {
$frame .= ($masked === true) ? $payload[$i] ^ $mask[$i % 4] : $payload[$i];
}
return $frame;
}
Error
Warning: fsockopen(): unable to connect to ws://echo.websocket.org:80
(Unable to find the socket transport "ws" - did you forget to enable
it when you configured PHP?) in G:\XAMPP\htdocs\a\server.php on line
16
Warning: fwrite() expects parameter 1 to be resource, boolean given in
G:\XAMPP\htdocs\a\server.php on line 17 error:407024:Unable to find
the socket transport "ws" - did you forget to enable it when you
configured PHP?
If you are talking about connecting to your Websocket using Php, then YES, it is doable. There are a few libraries like Php WebSocket client or Websocket php that can connect to your websocket as a Client.
You can also check out this Websocket Client for an example.
Another Working Example without using any library and implementing the hybi10 frame encoding as per the specification:
$host = 'www.host.com'; // your websocket server
$port = 443;
$local = "http://localhost"; // url where this script runs | Client
$data = '{"id": 2,"command": "server_info"}'; // data to be sent
$head = "GET / HTTP/1.1"."\r\n".
"Upgrade: WebSocket"."\r\n".
"Connection: Upgrade"."\r\n".
"Origin: $local"."\r\n".
"Host: $host"."\r\n".
"Sec-WebSocket-Version: 13"."\r\n".
"Sec-WebSocket-Key: asdasdaas76da7sd6asd6as7d"."\r\n".
"Content-Length: ".strlen($data)."\r\n"."\r\n";
// WebSocket handshake
$sock = fsockopen($host, $port, $errno, $errstr, 2);
fwrite($sock, $head ) or die('error:'.$errno.':'.$errstr);
$headers = fread($sock, 2000);
fwrite($sock, hybi10Encode($data)) or die('error:'.$errno.':'.$errstr);
$wsdata = fread($sock, 2000);
fclose($sock);
var_dump(hybi10Decode($wsdata));
// hibi10 decoding of data
function hybi10Decode($data)
{
$bytes = $data;
$dataLength = '';
$mask = '';
$coded_data = '';
$decodedData = '';
$secondByte = sprintf('%08b', ord($bytes[1]));
$masked = ($secondByte[0] == '1') ? true : false;
$dataLength = ($masked === true) ? ord($bytes[1]) & 127 : ord($bytes[1]);
if($masked === true)
{
if ($dataLength === 126) {
$mask = substr($bytes, 4, 4);
$coded_data = substr($bytes, 8);
}
elseif ($dataLength === 127) {
$mask = substr($bytes, 10, 4);
$coded_data = substr($bytes, 14);
}
else {
$mask = substr($bytes, 2, 4);
$coded_data = substr($bytes, 6);
}
for ($i = 0; $i < strlen($coded_data); $i++) {
$decodedData .= $coded_data[$i] ^ $mask[$i % 4];
}
}
else {
if ($dataLength === 126) {
$decodedData = substr($bytes, 4);
}
elseif ($dataLength === 127) {
$decodedData = substr($bytes, 10);
}
else {
$decodedData = substr($bytes, 2);
}
}
return $decodedData;
}
// hibi10 encoding of data
function hybi10Encode($payload, $type = 'text', $masked = true) {
$frameHead = array();
$frame = '';
$payloadLength = strlen($payload);
switch ($type) {
case 'text':
// first byte indicates FIN, Text-Frame (10000001):
$frameHead[0] = 129;
break;
case 'close':
// first byte indicates FIN, Close Frame(10001000):
$frameHead[0] = 136;
break;
case 'ping':
// first byte indicates FIN, Ping frame (10001001):
$frameHead[0] = 137;
break;
case 'pong':
// first byte indicates FIN, Pong frame (10001010):
$frameHead[0] = 138;
break;
}
// set mask and payload length (using 1, 3 or 9 bytes)
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]);
}
// most significant bit MUST be 0 (close connection if frame too big)
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;
}
// convert frame-head to string:
foreach (array_keys($frameHead) as $i) {
$frameHead[$i] = chr($frameHead[$i]);
}
if ($masked === true) {
// generate a random mask:
$mask = array();
for ($i = 0; $i < 4; $i++) {
$mask[$i] = chr(rand(0, 255));
}
$frameHead = array_merge($frameHead, $mask);
}
$frame = implode('', $frameHead);
// append payload to frame:
for ($i = 0; $i < $payloadLength; $i++) {
$frame .= ($masked === true) ? $payload[$i] ^ $mask[$i % 4] : $payload[$i];
}
return $frame;
}
Lastly, you can send your byte data as a JSON object by encoding it to base64 first.
Check this SO Post to see how to do that. Hope this helps.
My unswer NO. You can not fully use the websocket client logick, using only the server part(for example php). Because the server side know anything about the browser. Server - receives a request and returns a static result. All magic in the browser is javascript. Javascript can dynamically listen all user events, post a query to server and insert a response from the server to the page. Websocket can not work without javascript in browser.
This is WebSocket definition:
WebSockets are a bi-directional, full-duplex, persistent connection
from a web browser to a server. Once a WebSocket connection is
established the connection stays open until the client or server
decides to close this connection. With this open connection, the
client or server can send a message at any given time to the other.
This makes web programming entirely event driven, not (just) user
initiated. It is stateful. As well, at this time, a single running
server application is aware of all connections, allowing you to
communicate with any number of open connections at any given time.
The only thing you can do, is learn node js. It will allow you to write the browser (client) part and server part on one language - javascript. But however this will be different parts of application, and you will use different approaches, to program each part
It's not what you want but could help. You can use Redis as a middleware. Use Redis publish/subscribe message system.
Redis publish/subscribe message system
I have a problem with my website (http://www.zurfaria.ga/1/), where I'm trying to check how many players are online. I have downloaded this GitHub repository (https://github.com/mattvh/MCServerStatus) so I can query my server, but I can't seem to echo it in my HTML Here is my HTML and the PHP
<?php
require_once('/onlinecheck/Server.php')
require_once('/onlinecheck/Stats.php')
require_once('/onlinecheck/StatsException.php')
class MCServerStatus {
public $server;
public $online, $motd, $online_players, $max_players;
public $error = "OK";
function __construct($url, $port = '25565') {
$this->server = array(
"zurfaria.fmc.pw" => $url,
"25565" => $port
);
if ( $sock = #stream_socket_client('tcp://'.$url.':'.$port, $errno, $errstr, 1) ) {
$this->online = true;
fwrite($sock, "\xfe");
$h = fread($sock, 2048);
$h = str_replace("\x00", '', $h);
$h = substr($h, 2);
$data = explode("\xa7", $h);
unset($h);
fclose($sock);
if (sizeof($data) == 3) {
$this->motd = $data[0];
$this->online_players = (int) $data[1];
$this->max_players = (int) $data[2];
}
else {
$this->error = "Cannot retrieve server info.";
}
}
else {
$this->online = false;
$this->error = "Cannot connect to server.";
}
}
}
?>
<h1>Players Online:</h1>
<?php
echo $server->online_players; //Outputs the number of players online
?>
The HTML in between this code is fine, it works. What can I do to fix this? (I've looked up how to use the echo but didn't really understand it...)
I want to connect to webSocket server with PHP, but for some reason do not succeed, but a displays message is "Connected".
PHP:
$host="i[..].herokuapp.com" ;
$port=443;
$timeout=30;
$sk=fsockopen($host,$port,$errnum,$errstr,$timeout) ;
echo $errstr;
if (!is_resource($sk)) {
exit("connection fail: ".$errnum." ".$errstr) ;
} else {
echo "Connected";
fwrite($sk, '{""mi":1,"ertek":"a"}') or die('Error:' . $errno . ':' . $errstr);
fclose($sk);
}
And Nodejs Websocket server:
var WebSocketServer = require("ws").Server;
var http = require("http");
var express = require("express");
var app = express();
var port = process.env.PORT || 5000;
app.use(express.static(__dirname + "/"));
var server = http.createServer(app);
server.listen(port);
var wss = new WebSocketServer({server: server});
wss.on("connection", function(ws) {
[...]
});
This working:
public function __construct() { }
public function __destruct()
{
$this->disconnect();
}
public function sendData($data, $type = 'text', $masked = true, $return = false)
{
if(!$this->_connected)
{
//echo "Not connected";
return false;
}
if( !is_string($data)) {
//echo "Not a string data was given.";
return false;
}
if (strlen($data) == 0)
{
return false;
}
$res = fwrite($this->_Socket, $this->_hybi10Encode($data, $type, $masked));
if($res === 0 || $res === false)
{
return false;
}
$buffer = ' ';
if($return){
while(!empty($buffer))
{
$buffer = fread($this->_Socket, 512);// drop?
}
return $buffer;
}else{
return true;
}
}
public function connect($host, $port = 80, $path = 'into.hu', $origin = true)
{
$this->_host = $host;
$this->_port = $port;
$this->_path = $path;
$this->_origin = $origin;
$key = base64_encode($this->_generateRandomString(16, false, true));
$header = "GET ws://".$host . " HTTP/1.1\r\n";
$header.= "Host: ".$host.":".$port."\r\n";
$header.= "Connection: Upgrade\r\n";
$header.= "Pragma: no-cache\r\n";
$header.= "Cache-Control: no-cache\r\n";
$header.= "Upgrade: websocket\r\n";
$header.= "Sec-WebSocket-Version: 13\r\n";
$header.= "User-Agent: Mozilla/5.0 (X11; Linux i686) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/42.0.2311.90 Safari/537.36\r\n";
$header.= "Accept-Language: hu,en;q=0.8,en-US;q=0.6,en-AU;q=0.4\r\n";
$header.= "Sec-WebSocket-Key: " . $key . "\r\n";
if($origin !== false)
{
$header.= "Origin: ".$path."\r\n";
$header.= "Sec-WebSocket-Origin: " . $origin . "\r\n";
}
$header.= "Sec-WebSocket-Extensions: permessage-deflate; client_max_window_bits\r\n\r\n";
$this->_Socket = fsockopen($host, $port, $errno, $errstr, 2);
//socket_set_timeout($this->_Socket, 0, 10000);
fwrite($this->_Socket, $header);
$response = fread($this->_Socket, 200);
if(!empty($response)){
$this->_connected = true;
}
/*
preg_match('#Sec-WebSocket-Accept:\s(.*)$#mU', $response, $matches);
if ($matches) {
$keyAccept = trim($matches[1]);
$expectedResonse = base64_encode(pack('H*', sha1($key . '258EAFA5-E914-47DA-95CA-C5AB0DC85B11')));
$this->_connected = ($keyAccept === $expectedResonse) ? true : false;
}
*/
return $this->_connected;
}
public function checkConnection()
{
$this->_connected = false;
// send ping:
$data = 'ping?';
#fwrite($this->_Socket, $this->_hybi10Encode($data, 'ping', true));
$response = #fread($this->_Socket, 300);
if(empty($response))
{
return false;
}
$response = $this->_hybi10Decode($response);
if(!is_array($response))
{
return false;
}
if(!isset($response['type']) || $response['type'] !== 'pong')
{
return false;
}
$this->_connected = true;
return true;
}
public function disconnect()
{
$this->_connected = false;
is_resource($this->_Socket) and fclose($this->_Socket);
}
public function reconnect()
{
sleep(2);
$this->_connected = false;
fclose($this->_Socket);
$this->connect($this->_host, $this->_port, $this->_path, $this->_origin);
}
private function _generateRandomString($length = 10, $addSpaces = true, $addNumbers = true)
{
$characters = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!"§$%&/()=[]{}';
$useChars = array();
// select some random chars:
for($i = 0; $i < $length; $i++)
{
$useChars[] = $characters[mt_rand(0, strlen($characters)-1)];
}
// add spaces and numbers:
if($addSpaces === true)
{
array_push($useChars, ' ', ' ', ' ', ' ', ' ', ' ');
}
if($addNumbers === true)
{
array_push($useChars, rand(0,9), rand(0,9), rand(0,9));
}
shuffle($useChars);
$randomString = trim(implode('', $useChars));
$randomString = substr($randomString, 0, $length);
return $randomString;
}
private function _hybi10Encode($payload, $type = 'text', $masked = true)
{
$frameHead = array();
$frame = '';
$payloadLength = strlen($payload);
switch($type)
{
case 'text':
// first byte indicates FIN, Text-Frame (10000001):
$frameHead[0] = 129;
break;
case 'close':
// first byte indicates FIN, Close Frame(10001000):
$frameHead[0] = 136;
break;
case 'ping':
// first byte indicates FIN, Ping frame (10001001):
$frameHead[0] = 137;
break;
case 'pong':
// first byte indicates FIN, Pong frame (10001010):
$frameHead[0] = 138;
break;
}
// set mask and payload length (using 1, 3 or 9 bytes)
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]);
}
// most significant bit MUST be 0 (close connection if frame too big)
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;
}
// convert frame-head to string:
foreach(array_keys($frameHead) as $i)
{
$frameHead[$i] = chr($frameHead[$i]);
}
if($masked === true)
{
// generate a random mask:
$mask = array();
for($i = 0; $i < 4; $i++)
{
$mask[$i] = chr(rand(0, 255));
}
$frameHead = array_merge($frameHead, $mask);
}
$frame = implode('', $frameHead);
// append payload to frame:
$framePayload = array();
for($i = 0; $i < $payloadLength; $i++)
{
$frame .= ($masked === true) ? $payload[$i] ^ $mask[$i % 4] : $payload[$i];
}
return $frame;
}
private function _hybi10Decode($data)
{
$payloadLength = '';
$mask = '';
$unmaskedPayload = '';
$decodedData = array();
// estimate frame type:
$firstByteBinary = sprintf('%08b', ord($data[0]));
$secondByteBinary = sprintf('%08b', ord($data[1]));
$opcode = bindec(substr($firstByteBinary, 4, 4));
$isMasked = ($secondByteBinary[0] == '1') ? true : false;
$payloadLength = ord($data[1]) & 127;
switch($opcode)
{
// text frame:
case 1:
$decodedData['type'] = 'text';
break;
case 2:
$decodedData['type'] = 'binary';
break;
// connection close frame:
case 8:
$decodedData['type'] = 'close';
break;
// ping frame:
case 9:
$decodedData['type'] = 'ping';
break;
// pong frame:
case 10:
$decodedData['type'] = 'pong';
break;
default:
return false;
break;
}
if($payloadLength === 126)
{
$mask = substr($data, 4, 4);
$payloadOffset = 8;
$dataLength = bindec(sprintf('%08b', ord($data[2])) . sprintf('%08b', ord($data[3]))) + $payloadOffset;
}
elseif($payloadLength === 127)
{
$mask = substr($data, 10, 4);
$payloadOffset = 14;
$tmp = '';
for($i = 0; $i < 8; $i++)
{
$tmp .= sprintf('%08b', ord($data[$i+2]));
}
$dataLength = bindec($tmp) + $payloadOffset;
unset($tmp);
}
else
{
$mask = substr($data, 2, 4);
$payloadOffset = 6;
$dataLength = $payloadLength + $payloadOffset;
}
if($isMasked === true)
{
for($i = $payloadOffset; $i < $dataLength; $i++)
{
$j = $i - $payloadOffset;
if(isset($data[$i]))
{
$unmaskedPayload .= $data[$i] ^ $mask[$j % 4];
}
}
$decodedData['payload'] = $unmaskedPayload;
}
else
{
$payloadOffset = $payloadOffset - 4;
$decodedData['payload'] = substr($data, $payloadOffset);
}
return $decodedData;
}
}
$WebSocketClient = new WebsocketClient();
$WebSocketClient->connect('i[..].herokuapp.com',80,'valami.hu');
//$WebSocketClient->reconnect();
$WebSocketClient->sendData('üzenet küldés');
unset($WebSocketClient);
?>
I am writing a WebSocket server. While handshaking is successful and server can send encoded data using RFC standard, socket_select() can only detect changes when a new client is connected, not when the client send data to the server. What is happening?
class Server{
private $address;
private $port;
private $master;
private $sockets;
private $stream_sockets;
private $clients;
private $verbose_mode;
function __construct($address = '127.0.0.1', $port = 5001, $verbose_mode = true){
$this->address = $address;
$this->port = $port;
$this->verbose_mode = $verbose_mode;
$this->console("Socket server is starting...");
//socket creation
$socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
if(!socket_set_option($socket, SOL_SOCKET, SO_REUSEADDR, 1))
{
$this->console("Failed to set socket option: ".socket_strerror(socket_last_error()));
}
if(!socket_set_nonblock($socket))
{
$this->console("Failed to set socket nonblock: ".socket_strerror(socket_last_error()));
}
if(!is_resource($socket))
{
$this->console("Failed to create socket: ".socket_strerror(socket_last_error()));
}
if(!socket_bind($socket, $this->address, $this->port))
{
$this->console("Failed to bind socket: ".socket_strerror(socket_last_error()));
}
if(!socket_listen($socket, 20))
{
$this->console("Failed to listen: ".socket_strerror(socket_last_error()));
}
$this->master = $socket; //add current socket resource as master socket
$this->sockets = array($socket);//add current resource to all sockets
$this->console("Socket server started on {$this->address}:{$this->port}");
}
public function run(){
$this->console("Start running...");
$write = array();
$except = array();
while(isset($this->sockets[0])){
$changed_sockets = $this->sockets;
$result = socket_select($changed_sockets, $write, $except, 1 ,0);
//#stream_select($changed_sockets, $write = null, $except = null, 0, 5000);
if($result > 0)
{
$this->console("number of sockets: ".count($this->sockets));
$this->console("number of changed sockets: ".$result);
foreach($changed_sockets as $socket)
{
if($socket == $this->master)//self changed
{
if(($accepted_socket = socket_accept($this->master))!== false)//incoming connection
{
$this->connect($accepted_socket);//add as a client to the pool with info to be tracked without handshaking at first
}
else
{
$this->console("Socket error: ".socket_strerror(socket_last_error()));
}
}
else //must be others in sockets pool
{
$this->console("Finding socket associated with the client...");
$client = $this->get_client_by_socket($socket); //get client object to track them using socket that they are associated with
if($client){
$this->console("receiving data from the client.");
$bytes = #socket_recv($socket, $data, 2048, MSG_DONTWAIT);
$this->console("byte size received: $bytes");
if(!$client->get_handshake())//check if handshaking has done
{
$this->console("handshaking...");
$this->handshake($client, $data);//handshaking if it is not done previously
}
else if($bytes === 0)
{
$this->disconnect($client);
}
else
{
$this->console("incoming data from client {client->get_id()}");
$this->read($client, $data);//read from client if there are changes in sockets
}
}
}
}
}
}
}
private function slingshot($client, $read){
$send="00:00:00:00".",DM,SAY,0,".$read;
fwrite($client->get_stream_socket(), $send);//output to apollo
//workaround for apollo
if($client->get_initial())
{
$initial = 7;
$continue = 0;
}
else
{
$initial = 8;
$continue = 1;
}
while(TRUE)
{
//input from iris
$num = fgets($client->get_stream_socket(), $initial);//$number of words
if(ltrim($num) > 0)
{
$res = fgets($client->get_stream_socket(), ltrim($num)+1);
if($res!="")
{
fgets($fp,1);
$client->set_initial(false);
$res = $num.$res;
$res = substr($res,6+$continue);
//output to client
$message = rtrim($res);
send($client, $message);
break;
}
}
}
}
private function read($client, $received){
$read = $this->unmask($received);
$this->console("received from client: ".$read);
if($read == "##client exit##") {
$this->console("Killing a child process");
posix_kill($client->get_pid(), SIGTERM);
$this->console("Process {$client->get_pid()} is terminated.");
}
else
{
$this->console("start a child process");
$pid = pcntl_fork();
if($pid == -1)
{
die('could not fork.');
}
else if($pid)
{
$client->set_pid($pid);
}
else
{
//we are the child
$this->slingshot($client, $read);
}
}
}
private function disconnect($client){
$this->console("Disconnecting client #{$client->get_id()}");
$i = array_search($client, $this->clients);//search client in clients pool
$j = array_search($client->get_socket(), $this->sockets);//search client's socket in socket pool
if($j >= 0)
{
array_splice($this->sockets, $j, 1);
socket_close($client->get_socket());
$this->console("Socket closed.");
}
if($i >= 0)
{
array_splice($this->clients, $i, 1);
}
$this->console("Client #{$client->get_id()} disconnected.");
}
private function unmask($payload) {
$length = ord($payload[1]) & 127;
if($length == 126)
{
$masks = substr($payload, 4, 4);
$data = substr($payload, 8);
}
elseif($length == 127)
{
$masks = substr($payload, 10, 4);
$data = substr($payload, 14);
}
else
{
$masks = substr($payload, 2, 4);
$data = substr($payload, 6);
}
$text = '';
for ($i = 0; $i < strlen($data); ++$i){
$text .= $data[$i] ^ $masks[$i%4];
}
return $text;
}
private function encode($text){
// 0x1 text frame (FIN + opcode)
$b1 = 0x80 | (0x1 & 0x0f);
$length = strlen($text);
if($length <= 125)
{
$header = pack('CC', $b1, $length);
}
elseif($length > 125 && $length < 65536)
{
$header = pack('CCS', $b1, 126, $length);
}
elseif($length >= 65536)
{
$header = pack('CCN', $b1, 127, $length);
}
return $header.$text;
}
private function send($client, $text){
$this->console("Client {$client->get_id()}<<".$text);
$text = $this->encode($text);
if(socket_write($client->get_socket(), $text, strlen($text)) === false) {
$this->console("Unable to write to client #{$client->get_id()}'s socket");
$this->disconnect($client);
}
}
private function start_process(){
$this->console("start a child process");
$pid = pcntl_fork();
if($pid == -1)
{
die('could not fork.');
}
else if($pid)
{
$client->set_pid($pid);
}
else
{
//we are the child
$this->send($client, "something to be sent.");
}
}
private function handshake($client, $headers){//data as headers
$this->console("Getting client WebSocket version...");
if(preg_match("/Sec-WebSocket-Version: (.*)\r\n/", $headers, $match))
{
$version = $match[1];
}
else
{
$this->console("The client doesn't support WebSocket.");
}
$this->console("Client WebSocket version is {$version}, (required: 13)");
if($version == 13)
{
$this->console("Getting headers...");
if(preg_match("/GET (.*) HTTP/", $headers, $match))
{
$root = $match[1];
}
if(preg_match("/Host: (.*)\r\n/", $headers, $match))
{
$host = $match[1];
}
if(preg_match("/Origin: (.*)\r\n/", $headers, $match))
{
$origin = $match[1];
}
if(preg_match("/Sec-WebSocket-Key: (.*)\r\n/", $headers, $match))
{
$key = $match[1];
}
$this->console("client Headers are:");
$this->console("\t- Root: ".$root);
$this->console("\t- Host: ".$host);
$this->console("\t- Origin: ".$origin);
$this->console("\t- Sec-WebSocket-Key: ".$key);
$this->console("Generating Sec-WebSocket-Accept key...");
$acceptKey = $key.'258EAFA5-E914-47DA-95CA-C5AB0DC85B11';
$acceptKey = base64_encode(sha1($acceptKey, true));
$upgrade = "HTTP/1.1 101 Switching Protocols\r\n".
"Upgrade: websocket\r\n".
"Connection: Upgrade\r\n".
"Sec-WebSocket-Accept: $acceptKey".
"\r\n\r\n";
$this->console("sending this response to the client #{$client->get_id()}:\r\n".$upgrade);
socket_write($client->get_socket(), $upgrade);
$client->set_handshake(true);
$this->console("Handshake is successfully done!");
return true;
}
else
{
$this->console("WebSocket version 13 is required (the client supports version {$version})");
return false;
}
}
private function get_client_by_socket($socket){
foreach($this->clients as $client)//get all client objects from the pool and check one by one
{
if($client->get_socket() == $socket)//if socket returned from the client matches with parameter
{
$this->console("client found");
return $client;
}
}
return false;//no such client
}
private function connect($socket){
$this->console("creating client...");
$client_id = uniqid();
while(true){
$stream_socket = #stream_socket_client("tcp://127.0.0.1:10000", $errno, $errstr);
if($stream_socket)
{
$this->console("Apollo client created for client #$client_id.");
break;
}
else
{
$this->console("creation failed. Attempting to recreate Apollo client.");
}
}
$client = new Client($client_id, $socket, $stream_socket);
$this->clients[] = $client; //add the socket as client to be tracked
$this->sockets[] = $socket;//add socket as resource to sockets pool
$this->stream_sockets[] = $stream_socket;//add socket as resource to stream sockets pool
$this->console("Client #{$client->get_id()} is successfully created!");
}
private function console($text, $continue = true){
if(!$continue)
{
die($text);
}
if($this->verbose_mode)
{
echo date('[Y-m-d H:i:s] ').$text."\r\n";
}
}
}
That's because you have to accept the new incoming connection using socket_accept(), passing in the socket you've used for socket_listen().
The resulting socket can be used to check for incoming data as expected.
Edit
It seems that you forgot to add $write = $this->sockets; before your call to socket_select().
I figured out that to enable the socket select to detect data from the client, socket server has to send a dummy message to the client first immediately after handshake.