WebSocket Events Not Firing - javascript

I'm trying to create a simple WebSocket example using the HTML5/JS API. Based on what I trace out on the server, it seems like the socket is connecting, but none of the events fire (onopen, onmessage, onclose, etc). I'm a Flash developer so I'm not very good at debugging the JavaScript and I'm hoping someone can help me out. Here's the client side code I'm using:
<script type="text/javascript" charset="utf-8">
function startSocket()
{
if("WebSocket" in window)
{
var ws = new WebSocket("ws://localhost:1740");
ws.onopen = function() {
window.alert("open!");
}
ws.onmessage = function(event) {
window.alert(event.data);
}
ws.onclose = function() {
window.alert("Closed");
}
ws.onerror = function() {
window.alert("trouble in paradise");
}
}
}
</script>
And here's my socket server code (which works just fine from Flash, but that may not mean anything):
<?php
create_connection('localhost',1740);
function create_connection($host,$port)
{
$socket = socket_create(AF_INET,SOCK_STREAM,SOL_TCP);
if (!is_resource($socket)) {
echo 'Unable to create socket: '. socket_strerror(socket_last_error()) . PHP_EOL;
} else {
echo "Socket created.\n";
}
if (!socket_set_option($socket, SOL_SOCKET, SO_REUSEADDR, 1)) {
echo 'Unable to set option on socket: '. socket_strerror(socket_last_error()) . PHP_EOL;
} else {
echo "Set options on socket.\n";
}
if (!socket_bind($socket, $host, $port)) {
echo 'Unable to bind socket: '. socket_strerror(socket_last_error()) . PHP_EOL;
} else {
echo "Socket bound to port $port.\n";
}
if (!socket_listen($socket,SOMAXCONN)) {
echo 'Unable to listen on socket: ' . socket_strerror(socket_last_error());
} else {
echo "Listening on the socket.\n";
}
while (true)
{
$connection = #socket_accept($socket);
if($connection)
{
echo "Client $connection connected!\n";
send_data($connection);
} else {
echo "Bad connection.";
}
}
}
function send_data($connection)
{
echo $connection;
// Create a number between 30 and 32 that will be our initial stock price.
$stock_price = rand(30,32);
while (true)
{
socket_write($connection,"$stock_price\n",strlen("$stock_price\n"));
sleep(1);
// Generate a random number that will represent how much our stock price
// will change and then make that number a decimal and attach it to the
// previous price.
$stock_offset = rand(-50,50);
$stock_price = $stock_price + ($stock_offset/100);
echo "$stock_price\n";
}
}
?>

Are you calling startSocket() somewhere else in your code?
I know this code works. You might be able to adapt it: http://github.com/dshaw/zombo-socket/blob/master/zombocom-client.html

Maybe this is completely obvious, but if anyone else gets this, the problem is that you need to add a handshake. In Flash this isn't required and I still don't fully understand it, but I was able to modify this project - http://code.google.com/p/phpwebsocket/ - and it worked as it was supposed to by adding the gethandshake code after my socket_accept code ran.

Related

server sent events unexpected stop

let me first say that I'm no expert in web development so I might have made a stupid mistake but no amount of googling seems to be helping. I need to have a single html page (preprocessed in php) to display occasional events fired by a "server" page residing on the same machine.
I've readapted the basic w3schools server sent events example as follows and it seemed to be working fine until last night, but today (still working when first tested) I added a simple table and a ref to an external (empty) js file to the html and events stopped being caught by the page. I decided to roll back to the working code but even that doesn't work anymore. I had to remove the files and restore from a backup!
I'm sure the sse.php code is being run since part of what it does is removing records from a sqlite3 database and that's happening.
Here's the code, I really hope you can help me because I really have no idea what's happening.
This was tested on Linux + Xampp + Firefox and sadly this is a mandatory combination, having it work under other conditions is not useful at the moment. (fyi: opening the mon.php page in Opera gave me a single event and then stopped working as well)
Thank you all.
mon.php
<?php
if ( ! isset($_GET['mon']) ) {
die('mon code missing');
}
?>
<html>
<head>
<script type="text/javascript">
var evtSourceUrl = "sse.php?mon=" + <?php echo '"'.$_GET['mon'].'"'?>;
if(typeof(EventSource) !== "undefined") {
var source = new EventSource(evtSourceUrl);
source.onmessage = function(event) {
document.getElementById("info").innerHTML += event.data + "<br>";
};
} else {
document.getElementById("info").innerHTML = 'sse not supported';
}
</script>
</head>
<body>
<p>
<span id="info"></span>
</p>
</body>
</html>
sse.php
<?php
function output_sse($msg) {
echo "data: " . $msg . "\n\n";
ob_end_flush();
flush();
}
header('Content-Type: text/event-stream');
header('Cache-Control: no-cache');
header('Connection: keep-alive');
$mon = null;
if ( isset($_GET["mon"]) ) {
$mon = $_GET["mon"];
} else {
output_sse('mon code missing');
die();
}
while ( true ) {
usleep(1000 * 100);
$db = new PDO("sqlite:ch.sqlite3");
if ( $db === false ) {
output_sse('err:PDO');
die();
}
$stmt_select = $db->query("SELECT * FROM CH WHERE IDMON='$mon';");
$stmt_delete = $db->prepare("DELETE FROM CH WHERE IDMON='$mon';");
$db->beginTransaction();
$res = $stmt_select->fetch();
$stmt_delete->execute();
$db->commit();
$db->close();
if ( strlen($res['TK']) > 0 && strlen($res['SP']) > 0 ) {
$msg = "$res['TK'] :: $res['SP']";
output_sse($msg);
}
}
?>
add.php (to add new records to be displayed - this works)
<?php
$mon = isset($_GET["mon"]) ? $_GET["mon"] : die ('mon code missing') ;
$tk = isset($_GET["tk"]) ? $_GET["tk"] : die ('tk code missing') ;
$sp = isset($_GET["sp"]) ? $_GET["sp"] : die ('sp code missing') ;
$db = new SQLite3('ch.sqlite3');
if ( $db === false ) {
die('Cannot open db');
}
$res = $db->exec("INSERT INTO CH('IDMON','TK','SP') VALUES('$mon','$tk','$sp');");
if ( $res != 1 ) {
echo 'insert failed';
}
if ( $db->close() === false ) {
die('Cannot close connection to db');
}
echo('ok');
?>
This seems to be a problem related to the PDO interface in the sse.php file. I replaced it with the SQLite3 class like the add.php file and everything started working fine. The transaction seemed to get stuck.

Upgrading my PHP chat system? (Making it only update new messages?)

JS:
"use strict";
$(document).ready(function () {
var chatInterval = 250; //refresh interval in ms
var $userName = $("#userName");
var $chatOutput = $("#chatOutput");
var $chatInput = $("#chatInput");
var $chatSend = $("#chatSend");
function sendMessage() {
var userNameString = $userName.val();
var chatInputString = $chatInput.val();
$.get("./write.php", {
username: userNameString,
text: chatInputString
});
$userName.val("");
retrieveMessages();
}
function retrieveMessages() {
$.get("./read.php", function (data) {
$chatOutput.html(data); //Paste content into chat output
});
}
$chatSend.click(function () {
sendMessage();
});
setInterval(function () {
retrieveMessages();
}, chatInterval);
});
Write.php:
<?php
require("connect.php");
//connect to db
$db = new mysqli($db_host,$db_user, $db_password, $db_name);
if ($db->connect_errno) {
//if the connection to the db failed
echo "Failed to connect to MySQL: (" . $db->connect_errno . ") " . $db->connect_error;
}
//get userinput from url
$username=substr($_GET["username"], 0, 32);
$text=substr($_GET["text"], 0, 128);
//escaping is extremely important to avoid injections!
$nameEscaped = htmlentities(mysqli_real_escape_string($db,$username)); //escape username and limit it to 32 chars
$textEscaped = htmlentities(mysqli_real_escape_string($db, $text)); //escape text and limit it to 128 chars
//create query
$query="INSERT INTO chat (username, text) VALUES ('$nameEscaped', '$textEscaped')";
//execute query
if ($db->real_query($query)) {
//If the query was successful
echo "Wrote message to db";
}else{
//If the query was NOT successful
echo "An error occured";
echo $db->errno;
}
$db->close();
?>
Read.php
<?php
require("connect.php");
//connect to db
$db = new mysqli($db_host,$db_user, $db_password, $db_name);
if ($db->connect_errno) {
//if the connection to the db failed
echo "Failed to connect to MySQL: (" . $db->connect_errno . ") " . $db->connect_error;
}
$query="SELECT * FROM chat ORDER BY id ASC";
//execute query
if ($db->real_query($query)) {
//If the query was successful
$res = $db->use_result();
while ($row = $res->fetch_assoc()) {
$username=$row["username"];
$text=$row["text"];
$time=date('G:i', strtotime($row["time"])); //outputs date as # #Hour#:#Minute#
echo "<p>$time | $username: $text</p>\n";
}
}else{
//If the query was NOT successful
echo "An error occured";
echo $db->errno;
}
$db->close();
?>
Basically everything works perfectly, except I want to allow people to copy and paste, but what the script is doing at the moment is updating every message at the chatinterval which is 250MS.
How can I make it so I can highlight a message and copy it?
So my question is, can I do this:
Can I make it only update the new messages that appear every 250-500MS instead of updating every last bit of HTML as that is a waste of resources (Especially if there was a lot of messages)
I hope you can help!
p.s. I don't want to use web sockets
To make it update just starting from the last message, get the ID of the last message, and then in your next $.get include the id of that message and get only messages that came after that.
And then use .append() in your javascript so you're not overwriting the whole thing.
It looks like you're already using jQuery. You can create a PHP script that only queries the database for entries newer than the newest one displayed, then use $.append to append the message to the <div> (or whatever other element) that holds it.
Also, as the commenter pointed out, you're still probably susceptible to SQL injection. Considering using PDO with prepared SQL statements.

Ajax function sends GET request but PHP never process it

I am trying to use Ajax to run a function in a PHP script. My two script files are as follows:
get.js:
$.ajax({
url: "testPhp.php",
data: { param1: "INITIALIZE"},
type: "GET",
context: document.body
}).done(function() {
alert("DONE!");
}).fail(function() {
console.log(arguments);
});
testPhp.php:
<?php
define("SERVER_NAME", "localhost");
define("USERNAME", "root");
define("PASSWORD", "");
define("DATABASE", "myDB");
//Print database info
echo nl2br("Server Name: " . SERVER_NAME . "\nUsername: " . USERNAME . "\nPassword: " . PASSWORD);
//Connecting to database
$mysqli = mysqli_connect(SERVER_NAME, USERNAME, PASSWORD);
//Check database connection
if($mysqli === false) {
die ("\nCould not connect: " . mysqli_connect_error());
} else {
echo nl2br("\nConnected successfully! Host info: " . mysqli_get_host_info($mysqli));
}
//Function to execute database queries
function executeQuery($sql_query, $mysqli) {
if(mysqli_query($mysqli, $sql_query)){
echo nl2br("\n\nQuery executed successfully: $sql_query");
} else {
echo nl2br("\n\nERROR: Could not able to execute $sql_query. " . mysqli_error($mysqli));
}
}
function initializeDatabase() {
//Query to create flashcards database
$sql = "CREATE DATABASE IF NOT EXISTS " . DATABASE;
executeQuery($sql, $mysqli);
}
if(isset($_GET["param1"])) {
$arg = $_GET["param1"];
if($arg == "INITIALIZE") {
initializeDatabase();
}
}
testPhp.php contains other methods, but none are called yet. When I run the PHP script with the code of initializeDatabase() outside of the function, so it will automatically run, it works perfectly. The alert() also occurs a couple seconds after I load my webpage, when the script is run, so it seems like it is doing something during the run of the function before exiting. However, when I use the Ajax GET request, it seems as if PHP is not responding. Any ideas?
It could be failing because in the function initializeDatabase(), $mysqli is an undefined variable. Try passing $mysqli to initializeDatabase().

PHP stream websockets

Im kinda new with the sockets stuff and Im trying to make a server on PHP to support websockets calls from my javascript currently my code looks like this
<?php
class Websocket
{
private $server;
private $sockets = [];
public function create($host)
{
$this->server = stream_socket_server('tcp://localhost:8080', $errno, $errmsg);
stream_set_blocking($this->server, 0);
}
public function run()
{
while(true)
{
$client = stream_socket_accept($this->server);
if($client)
{
$data = stream_socket_recvfrom($client, 2048);
if($data)
{
echo 'Client connected'.PHP_EOL;
echo $data;
$response = $this->handshake($data);
stream_socket_sendto($client, $response);
}
}
}
}
private function handshake($data)
{
$data = explode(PHP_EOL, $data);
foreach($data as $header)
{
$current_header = explode(':', $header);
if($current_header[0] == 'Sec-WebSocket-Key')
{
$accept = base64_encode(sha1(trim($current_header[1]).'258EAFA5-E914-47DA-95CA-C5AB0DC85B11', true));
$response = 'HTTP/1.1 101 Switching Protocols'.PHP_EOL.'Upgrade: websocket'.PHP_EOL.'Connection: Upgrade'.PHP_EOL.'Sec-WebSocket-Accept:'.$accept.PHP_EOL.PHP_EOL;
return $response;
}
}
}
}
And my javascript is just a simple
var socket = new WebSocket('ws://localhost:8080');
socket.onopen = function(event)
{
console.log('connected');
socket.send('hello');
}
Currently the message connected appears on my chrome console but after that when the hello message is supposed to be sent I get this error
"connection to: xxx was interrupted while the page was loading"
So my question is after I have successfully send the handshake to the client how do I process messages? I know my code is always sending the handshake to new connections but on my server I will only see the first message beeing echoed (the http request) and not the "hello" one
You need to handle the message -
socket.onmessage = function(e){
var server_message = e.data;
console.log(server_message);
}

Have a PHP server script persistently listen on a socket non blocking?

I am writing a project that is in 2 parts.
So far I have a front end View.php (HTML5,CSS3,JQuery) and this will query the server.php
The server PHP opens a TCP socket to a server and listens in and can make commands by writing to the socket.
The normal procedure now goes like this
View.php -> Calls using rest API to server.php
Server.php -> Connects to TCP -> Reads from TCP -> Json_encodes & print -> close TCP socket connection.
What I want to achieve is a script Server.php that once started. It constantly listens in to a server, until it gets a shutdown command. I want to keep a fsocket connection open. Any thoughts?
The answer is using non blocking programming. In PHP we have specific function for non blocking I/O. For sockets you should use socket_set_nonblock function on a socket resource.
$port = 8081;
$address = '127.0.0.1';
if (($sock = socket_create(AF_INET, SOCK_STREAM, SOL_TCP)) === false) {
echo "socket_create() failed: reason: " . socket_strerror(socket_last_error()) . "\n";
exit();
}
if (socket_bind($sock, $address, $port) === false) {
echo "socket_bind() failed: reason: " . socket_strerror(socket_last_error($sock)) . "\n";
exit();
}
if (socket_listen($sock, 5) === false) {
echo "socket_listen() failed: reason: " . socket_strerror(socket_last_error($sock)) . "\n";
}
socket_set_nonblock($sock);
echo "listening for new connection".PHP_EOL;
$conneted_clients = [];
do {
$clientsock = socket_accept($sock);
if($clientsock !== false){
socket_set_nonblock($clientsock);
$conneted_clients[] = $clientsock;
socket_getpeername($clientsock,$address);
echo "New Connection from: ".$address.PHP_EOL;
$msg = PHP_EOL."Welcome to the PHP Test Server. " . PHP_EOL.
"To quit, type 'quit'. To shut down the server type 'shutdown'." . PHP_EOL;
socket_write($clientsock, $msg, strlen($msg));
}
$status = check_clients($conneted_clients);
if(!$status) break;
usleep(500000);
} while (true);
function check_clients($clients)
{
foreach($clients as $key => $con)
{
if(get_resource_type($con) !== "Socket")
{
socket_getpeername($clientsock,$address);
echo $address." has diconnected.".PHP_EOL;
unset($clients[$key]);
continue;
}
if (false === $buff = socket_read($con, 2048)) {
continue;
}
$buff = trim($buff);
if ($buff == 'quit') {
socket_close($con);
unset($clients[$key]);
continue;
}
if (trim($buff) == 'shutdown') {
socket_close($con);
echo "shutdown initiated".PHP_EOL;
return FALSE;
}
if($buff != false || $buff != null)
{
$talkback = "PHP: You said '$buff'.".PHP_EOL;
socket_write($con, $talkback, strlen($talkback));
echo "$buff".PHP_EOL;
}
}
return TRUE;
}
echo "Closing Server";
socket_close($sock);

Categories

Resources