chrome app TcpServer and php client - javascript

I'm use example from Google Team to create a TCP Server using Chrome App Extension API. Sample is work correctly and I connect via telnet and send commands.
When I'm trying to connect to this server from client and try send data. Client connected to server and send data, but server not receive data. Client on PHP, for test I'm using this example.
What I doing wrong?:(
Thx.

Solve: I'm resolve problem. In php script, after connect need delay. I'm using usleep function. All worked
Worked Example:
$fp = pfsockopen("ip", port, $errno, $errstr, 30);
if (!$fp) {
echo "$errstr ($errno)<br />\n";
} else {
$out = "minimize";
usleep(125000);
$r = fputs($fp, $out);
sleep(1); //
$out = "restore";
$r = fputs($fp, $out);
usleep(125000);
fclose($fp);
}

Related

How to connect to friendly URL socket?

I accustomed to use HTML5 websockets on JavaScript, where you can connect with an instruction like this one:
var socket = new WebSocket("ws://localhost:8000/socket/server/socketEndpoint");
I need to do a similar connection but with PHP. According to the documentation, I can use "socket_connect", but I need an IP address and a PORT. I have the port, but is inside the URL and I don't know how to use it in socket_connect.
Any ways to connect to that URL with PHP? I need another instruction? Thanks to all.
You can use Pawl for that (an asynchronous WebSocket client in PHP).
You can install it via composer: composer require ratchet/pawl
Using your connection details, the result would be:
<?php
require __DIR__.'/vendor/autoload.php';
\Ratchet\Client\connect('ws://localhost:8000/socket/server/socketEndpoint')->then(function($conn) {
$conn->on('message', function($msg) use ($conn) {
echo "Received: {$msg}\n";
$conn->close();
});
$conn->send('Hello World!');
}, function ($e) {
echo "Could not connect: {$e->getMessage()}\n";
});

How to connect Server Sents Events (SSE) to a PHP MVC Controller

So I currently have a working SSE system, which sends out notifications to clients. For the EventSource I specify a direct script on the server notifs.php.
Simplified this looks like following:
client.js
$(window).on('pageshow',function(){
// Server Sent Events here
if(typeof(EventSource) !== "undefined") {
var source = new EventSource("notifs.php");
source.onmessage = function(event) { ... };
}
});
And PHP side looks something like this:
notifs.php
header('Content-Type: text/event-stream');
header('Cache-Control: no-cache');
echo 'data: {"Foo": "Bar}'.PHP_EOL;
echo PHP_EOL;
ob_flush();
flush();
Now this works well, but I'd like to structure my whole project under the MVC design pattern, so instead of connecting the EventSource to "notifs.php" I'd like to have something like "/notification/notifs/", where notification is a Controller and notifs it's action.
Firefox tells me that it cannot create a connection to localhost/notification/notifs/. I would assume that this happens, because this is no real address on the server. While normal HTTP-requests go through a routing engine, this does not.
I wasn't able to find any information about this. Is it even possible to include the SSE endpoint in an object-oriented class?
Or do they always have to be in their own files?

How to connect to local API created by using PHP from Vue.js 2

I've created a small API using Slim Framework (PHP) and I want to connect to it from my Vue.js application. How can I do this? I keep my API in Open Server. Path: http://localhost/restapi.loc/api/customers. Via this path I can easily get my data in browser. But what about the Vue.js app?
Here's my API:
<?php
use \Psr\Http\Message\ServerRequestInterface as Request;
use \Psr\Http\Message\ResponseInterface as Response;
$app = new \Slim\App;
$app->get('/api/customers', function(Request $request, Response $response) {
$db = new DB();
$db = $db->Connect();
$sql = "SELECT * FROM workers";
$result = $db->query($sql);
return json_encode($result->fetch_assoc());
$db->close();
});
That's the way how I'm trying to reach the API:
getCustomers() {
this.$http.get('http://localhost/restapi.loc/api/customers')
.then(function(response){
console.log(JSON.parse(response.body));
});
}
But it doesn't work. I'd really appreciate every response from your side.

internal server error on XMLHttpRequest

I have a chrome extension that only runs on Facebook and I am trying to send data that the extension gathers to a MySQL database that I have on my GoDaddy website server. I keep getting the error message "Failed to load resource: the server responded with a status of 500 (Internal Server Error)". I wasn't sure what the issue is since I'm just getting into web development.
Here is my code for the content script on my chrome extension:
var dummyUrl = new URL ("http://www.bbc.com/news/world-us-canada-41081629");
console.log("dummyUrl: " + dummyUrl);
//Create XMLHttpRequest Object
var xhttp = new XMLHttpRequest();
//Send request
xhttp.open("POST", "https://pocketchange.social/data.php", true);
xhttp.send(dummyUrl);
And here is my PHP file on my webserver that is running a query to send the data to my database:
<?php
$mysqli = new mysqli("localhost", "Jarid", "Database", "myURL");
//Check connection
if(mysqli === false) {
die("ERROR: Could not connect" . $mysqli->connect_error;
}
//Print host information
echo "Connection successful. Host info: " . $mysqli->host_info;
//Escape user inputs
$url = $mysqli->real_escape_string($_REQUEST['url']);
$description = $mysqli->real_escape_string($_REQUEST['description']);
$keywords = $mysqli->real_escape_string($_REQUEST['keywords']);
$content = $mysqli->real_escape_string($_REQUEST['content']);
$language = $mysqli->real_escape_string($_REQUEST['language']);
//Execute query
$query = "INSERT INTO url_data (url, description, keywords, content, language) VALUES ('$url', '$description', '$keywords', '$content', '$language')";
//Checking to see if values were inserted properly
if($mysqli->query($query) === true) {
echo "Data successfully inserted.";
}
else {
echo "ERROR could not execute query" . $mysqli->error;
}
$mysqli->close();
?>
Is my issue mainly that I'm trying to send data to a completely different server? I'm not super clear on how all of these pieces communicate with each other (ie how does the chrome extension know how to connect to the GoDaddy server, and how exactly is the php file sending data to the database, etc.)
Thanks in advance.
Regarding the "500 (Internal Server Error)", this highlighted SO post could give you some idea.
The 500 code would normally indicate an error on the server, not
anything with your code. Some thoughts
Talk to the server developer for more info. You can't get more info directly.
Verify your arguments into the call (values). Look for anything you might think could cause a problem for the server process. The process
should not die and should return you a better code, but bugs happen
there also.
Could be intermittent, like if the server database goes down. May be worth trying at another time
You can check the post for some possible answer as well.
Hope this helps.

Socket Programming Cross Platform (PHP & Javascript)

I have created a socket server using PHP, the code is like this
PHP
function listen()
{
// set some variables
$host = "127.0.0.1";
$port = 25003;
// don't timeout!
set_time_limit(0);
// create socket
$socket = socket_create(AF_INET, SOCK_STREAM, 0) or die("Could not create socket\n");
// bind socket to port
$result = socket_bind($socket, $host, $port) or die("Could not bind to socket\n");
// start listening for connections
$result = socket_listen($socket, 3) or die("Could not set up socket listener\n");
// accept incoming connections
// spawn another socket to handle communication
$spawn = socket_accept($socket) or die("Could not accept incoming connection\n");
// read client input
$input = socket_read($spawn, 1024) or die("Could not read input\n");
// clean up input string
$input = trim($input);
echo "Client Message : " . $input."\n";
// reverse client input and send back
$output = strrev($input) . "\n";
socket_write($spawn, $output, strlen($output)) or die("Could not write output\n");
// close sockets
socket_close($spawn);
socket_close($socket);
listen();
}
set_time_limit(0);
listen();
Taken from http://www.codeproject.com/Tips/418814/Socket-Programming-in-PHP
And I create the client socket using Javascript, like this
Javascript
<!DOCTYPE HTML>
<html>
<head>
<script type="text/javascript">
function WebSocketTest()
{
if ("WebSocket" in window)
{
alert("WebSocket is supported by your Browser!");
// Let us open a web socket
var ws = new WebSocket("ws://localhost:25003");
ws.onopen = function()
{
// Web Socket is connected, send data using send()
ws.send("Message to send");
alert("Message is sent...");
};
ws.onmessage = function (evt)
{
var received_msg = evt.data;
alert("Message is received...");
};
ws.onclose = function()
{
// websocket is closed.
alert("Connection is closed...");
};
}
else
{
// The browser doesn't support WebSocket
alert("WebSocket NOT supported by your Browser!");
}
}
</script>
</head>
<body>
<div id="sse">
Run WebSocket
</div>
</body>
</html>
Then I run the PHP server, it's work, it's listening.
And the I run the Javascript client, it's work, the PHP Server is receiving request from Javascript.
BUt the response from PHP is like this
I don't understand how to change the client message, let's say I want to send message just like "Hello",
1. How can I call it from javascript so the PHP server is receive only "Hello" ?
2. Anyone can explain to me what is the function of each url like this ?
ws://localhost:25003/daemon.php
what is the second parameter? is this connect to my php file? because I try to locate to my php it doesn't work.
PHP Socket server is OK, the problem is Javascript, it's sending a HTTP request and this send is a protocol for HTTP.
You can start the PHP Web Server on that port and answer that petisions whin Ajax queries.
Command line to start php like a Web Server
php -S 127.0.0.1:25003
The document root for WebServer is the same for PHP

Categories

Resources