Socket php to java when js event - javascript

So currently, I manage to communicate between php and java thanks to the socket. The problem is that once the java client is connected, I can't do anything anymore.
I would like that when a js event is triggered, information to the java client is transmitted.
How can I do that?
Thanks
My code php:
$host = "0.0.0.0";
$port = 6969;
set_time_limit(0);
$socket = socket_create(AF_INET, SOCK_STREAM, 0) or die("Create Error");
$result = socket_bind($socket, $host, $port) or die("Bind Error");
$result = socket_listen($socket, 3) or die("Listener Error");
$spawn = socket_accept($socket) or die("Accept Error");
$input = socket_read($spawn, 1024) or die("Read Error");
echo "Received: ".$input;
$output = "Received";
socket_write($spawn, $output, strlen($output)) or die("Write Error");
My java code:
Socket socket = new Socket("localhost", 6969);
PrintWriter writer = new PrintWriter(socket.getOutputStream());
writer.println("Test Message");
writer.flush();
BufferedReader reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
System.out.println(reader.readLine());

I will suggest you to use REST unless you have a very specific use case .
Else you need to close socket (on client * php ) and stream once you get the data.
https://docs.oracle.com/javase/tutorial/networking/sockets/readingWriting.html
read the explanation here, this will help you

Related

How to retrieve Data from Php while in Node.js

I just wanted to retrieve some PHP/Mysql stuff at the beginning of my app (authentication and x and y data) from the users which I later plan to emit to the app.js (one time at the beginning and once the user disconnects update x - y values).
So basically I have set up Nodes.js and understood that some stuff is not possible like before (e.g with plain php)
Where I already have a problem is the AJAX php request in the index.html of my nodes Server
Schema:
app.js: pull Data from the /Client/index.html (I think need to do it via sockets)
index.html: get or post data via Ajax to a php file and get the values of the database back to the index.html(JavaScript)
then send that data via sockets to the app.js
php: select mysql database
retrieve values from mysql
parse them via Json and make them available in the index.html file Nodes.js (Client)
Maybe somebody of you have a solution
Nodes.js /Client/index.html:
function checkuser(username, password) {
var myObj;
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
// Typical action to be performed when the document is ready:
myObj = xhttp.responseText;
var i = 0;
while (i <= myObj.length) {
//console.log("ASQL found and Auth Username:"+ myObj[i].username) ;
console.log(myObj.username);
i++;
}
}
};
xhttp.open("GET", "/client/is_user.php?username333=" + username + "&password333=" + password, true);
xhttp.send();
}
is_user.php:
<?php
require('config_sql.php');
$email = stripslashes($_GET['username333']);
$email = mysqli_real_escape_string($con,$email);
$password369 = stripslashes($_GET['password333']);
$password369 = mysqli_real_escape_string($con,$password369);
$query = "SELECT * FROM `users` WHERE email='$email'
and password='".md5($password369)."'";
$result = mysqli_query($con,$query) or die(mysql_error());
$response = array();
$rows = mysqli_num_rows($result);
while ($row_user= mysqli_fetch_assoc($result))
{
$response[] = $row;
}
$jsonData = json_encode($response);
echo $jsonData;
mysqli_close($con);
?>
atm is not retrieving the username form the created json on the php side.
If I console.log(myObj); it's showing the me complete php.file data as plain text if I want to retrieve the username from MySql its saying undefined.
Is the php Interpreter actually working when I post/get via Ajax in a Node.js environment?
Normally when I was programming with pure php all the request worked well.
Thank you in advance.
Check you code for recieving result from query:
$rows = mysqli_num_rows($result);
while ($row_user= mysqli_fetch_assoc($result))
{
$response[] = $row;
}
$jsonData = json_encode($response);
Should be so:
$rows = mysqli_num_rows($result);
while ($row_user= mysqli_fetch_assoc($result))
{
$response[] = $row_user;
}
$jsonData = json_encode($response);

500 Internal Server Error From PHP - Insert Data Into VFP9 Database

I'm trying to write an API script in PHP to insert records into a Foxpro 9 database but i'm getting the "500 Internal Server Error" message when the API is called. I'm a Foxpro developer but pretty new to PHP.
I've gone through several questions & comments on the topic on this site and other sites and have implemented almost all of the suggested solutions to no avail. Below are the steps i've taken so far:
IIS & PHP are installed and configured. (phpinfo() is displaying correctly)
VFP 9 is fully installed. (with VFPOLEDB driver)
I've fully cleared browsing data severally.
I'm not sure where the problem is (as the "500 internal server error" message could be a problem with the PHP script or PHP configuration. Could somebody please take a look at the PHP script below to help figure out the problem?
TIA.
<?php
// required headers
header("Access-Control-Allow-Origin: *");
header("Content-Type: application/json; charset=UTF-8");
header("Access-Control-Allow-Methods: POST");
header("Access-Control-Max-Age: 3600");
header("Access-Control-Allow-Headers: Content-Type, Access-Control-Allow-Headers, Authorization, X-Requested-With");
// database connection
$conn = new COM("ADODB.Connection");
$conn->Open("Provider=VFPOLEDB.1;Data Source=C:\inetpub\wwwroot\sonreceipt\RECEIPT.DBC;Collating Sequence=Machine");
// get posted data
$data = json_decode(file_get_contents("php://input"));
// set payment values received
$jrefnum = $data->refnum;
$jpaydate = $data->paydate;
$jcustname = $data->custname;
$jcustemail = $data->custemail;
$jdemandno = $data->demandno;
$jdemanddate = $data->demanddate;
$jamount = $data->amount;
$jrecpdesc = $data->recpdesc;
$jpaybank = $data->paybank;
$jpayref = $data->payref;
// create the payment
if(create()){
echo "Payment was created.";
}
// if unable to create the payment, tell the user
else {
echo "Unable to create payment.";
}
// create payment
function create(){
// query to insert record
$query = "INSERT INTO SON2100 (refnum, paydate, custname, custemail, demandno, demanddate, amount, recpdesc, paybank, payref)
VALUES ($srefnum, $spaydate, $scustname, $scustemail, $sdemandno, $sdemanddate, $smount, $srecpdesc, $spaybank, $spayref)";
// prepare query
global $conn
$stmt = $conn->prepare($query);
// sanitize
global $jrefnum, $jpaydate, $jcustname, $jcustemail, $jdemandno, $jdemanddate, $jamount, $jrecpdesc, $jpaybank, $jpayref;
$srefnum=htmlspecialchars(strip_tags($jrefnum));
$spaydate=htmlspecialchars(strip_tags($jpaydate));
$scustname=htmlspecialchars(strip_tags($jcustname));
$scustemail=htmlspecialchars(strip_tags($jcustemail));
$sdemandno=htmlspecialchars(strip_tags($jdemandno));
$sdemanddate=htmlspecialchars(strip_tags($jdemanddate));
$samount=htmlspecialchars(strip_tags($jamount));
$srecpdesc=htmlspecialchars(strip_tags($jrecpdesc));
$spaybank=htmlspecialchars(strip_tags($jpaybank));
$spayref=htmlspecialchars(strip_tags($jpayref));
// execute query
if($stmt->execute()){
return true;
}
return false;
}
?>
Below is the javascript that calls the API.
<script>
function sendData(data) {
var XHR = new XMLHttpRequest();
var jsonData = {"refnum":"1111-2222-3333", "paydate":"01-06-2018", "custname":"O. A. BECKLEY VENTURES", "custemail":"beckleyventures#gmail.com", "demandno":"DEMAND NOTE 001", "demanddate":"01-06-2018", "amount":"15550.00", "recpdesc":"SONCAP", "paybank":"ZENITH BANK PLC", "payref":"0123456789"};
// Define what happens on successful data submission
XHR.addEventListener('load', function(event) {
window.alert('Yeah! Data sent and response loaded.');
});
// Define what happens in case of error
XHR.addEventListener('error', function(event) {
window.alert('Oops! Something goes wrong.');
});
// Set up our request
XHR.open('POST', 'http://localhost/sonreceipt/api/create_payment.php', true);
// Add the required HTTP header for form data POST requests
XHR.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
// Finally, send our data.
XHR.send(jsonData);
}
</script>
Here is the edited script but still not working. As indicated earlier, i'm still new to PHP.
<?php
// required headers
header("Access-Control-Allow-Origin: *");
header("Content-Type: application/json; charset=UTF-8");
header("Access-Control-Allow-Methods: POST");
header("Access-Control-Max-Age: 3600");
header("Access-Control-Allow-Headers: Content-Type, Access-Control-Allow-Headers, Authorization, X-Requested-With");
// database connection
$conn = new COM("ADODB.Connection");
try {
$conn->Open('Provider=VFPOLEDB.1;DSN=RECEIPT;Mode=ReadWrite;Password="";Collating Sequence=MACHINE;');
if (! $conn) {
throw new Exception("Could not connect!");
}
}
catch (Exception $e) {
echo "Error (File:): ".$e->getMessage()."<br>";
}
if (!$conn)
{exit("Connection Failed: " . $conn);}
echo "Connection Sucessfull";
// get posted data
$data = json_decode(file_get_contents("php://input"));
// set payment values received
$jrefnum = $data->refnum;
$jpaydate = $data->paydate;
$jcustname = $data->custname;
$jcustemail = $data->custemail;
$jdemandno = $data->demandno;
$jdemanddate = $data->demanddate;
$jamount = $data->amount;
$jrecpdesc = $data->recpdesc;
$jpaybank = $data->paybank;
$jpayref = $data->payref;
// create the payment
if(create()){
echo "Payment was created.";
}
// if unable to create the payment, tell the user
else {
echo "Unable to create payment.";
}
// create payment
function create(){
global $conn;
global $jrefnum, $jpaydate, $jcustname, $jcustemail, $jdemandno, $jdemanddate, $jamount, $jrecpdesc, $jpaybank, $jpayref;
// sanitize
$srefnum=htmlspecialchars(strip_tags($jrefnum));
$spaydate=htmlspecialchars(strip_tags($jpaydate));
$scustname=htmlspecialchars(strip_tags($jcustname));
$scustemail=htmlspecialchars(strip_tags($jcustemail));
$sdemandno=htmlspecialchars(strip_tags($jdemandno));
$sdemanddate=htmlspecialchars(strip_tags($jdemanddate));
$samount=htmlspecialchars(strip_tags($jamount));
$srecpdesc=htmlspecialchars(strip_tags($jrecpdesc));
$spaybank=htmlspecialchars(strip_tags($jpaybank));
$spayref=htmlspecialchars(strip_tags($jpayref));
// query to insert record
$query = "INSERT INTO SON2100 (refnum, paydate, custname, custemail, demandno, demanddate, amount, recpdesc, paybank, payref)
VALUES ($srefnum, $spaydate, $scustname, $scustemail, $sdemandno, $sdemanddate, $smount, $srecpdesc, $spaybank, $spayref)";
// prepare query
$stmt = $conn->prepare($query);
// execute query
if($stmt->execute()){
return true;
}
return false;
}
?>
You haven't declared the variables used in the value portion of the SQL in your create() function and you're missing a semicolon
// you have
global $conn
// should be
global $conn ;
Use
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
to find your error.

WebSocket Server https

I'm new with websocket things. I tried to make a simple chat application, and i've followed ratchet hello world tutorial. I ran it locally with
'ws://localhost:8080'
It's works perfectly fine. I can chat via javascript console like the tutorials said. Now, i try to put it on my webserver https://some.domain.co/websocket. I've tried to do the same thing like
'ws://some.domain.co:8080'
'ws://some.domain.co:8080/websocket'
'ws://some.domain.co/websocket:8080'
'wss://some.domain.co:8080'
'wss://some.domain.co:8080/websocket'
'wss://some.domain.co/websocket:8080'
But none of them work. By browser still give error
WebSocket connection to 'wss://some.domain.co/' failed: Error during
WebSocket handshake: Unexpected response code: 200
or
WebSocket connection to 'wss://some.domain.co:8080/' failed: Error in connection establishment: net::ERR_TIMED_OUT
I think i had something wrong with my url. Any advice? Thanks before
Edit
chatServer.php
require dirname(__DIR__) . '/vendor/autoload.php';
use Ratchet\Server\IoServer;
use Ratchet\Http\HttpServer;
use Ratchet\WebSocket\WsServer;
include("Chat.php");
require dirname(__DIR__) . '/vendor/autoload.php';
$server = IoServer::factory(
new HttpServer(
new WsServer(
new Chat()
)
), 8080
);
$server->run();
Chat.php
use Ratchet\MessageComponentInterface;
use Ratchet\ConnectionInterface;
class Chat implements MessageComponentInterface {
protected $clients;
public function __construct() {
$this->clients = new \SplObjectStorage;
echo "Server is Running\n";
}
public function onOpen(ConnectionInterface $conn) {
// Store the new connection to send messages to later
$this->clients->attach($conn);
echo "New connection! ({$conn->resourceId})\n";
}
public function onMessage(ConnectionInterface $from, $msg) {
$numRecv = count($this->clients) - 1;
echo sprintf('Connection %d sending message "%s" to %d other connection%s' . "\n"
, $from->resourceId, $msg, $numRecv, $numRecv == 1 ? '' : 's');
foreach ($this->clients as $client) {
if ($from !== $client) {
// The sender is not the receiver, send to each client connected
$client->send($msg);
}
}
}
public function onClose(ConnectionInterface $conn) {
$this->clients->detach($conn);
echo "Connection {$conn->resourceId} has disconnected\n";
}
public function onError(ConnectionInterface $conn, \Exception $e) {
echo "An error has occurred: {$e->getMessage()}\n";
$conn->close();
}
}

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);
}

Creating a PHP websockets server

I am new in websockets technology. I was trying to create a websockets php server and connect to the server with a javascript client. I am using xampp 1.8.3.
I made this simple PHP server:
<?php
error_reporting(E_ALL);
set_time_limit(0);
$address = "127.0.0.1";
$port = 1777;
$maxConnections = 10;
if(!($sock = socket_create(AF_INET, SOCK_STREAM, 0))){
$errorCode = socket_last_error();
$errorMsg = socket_strerror($errorCode);
die("socket_create() failed -> {$errorCode}:{$errorMsg}\n");
}
echo "Server created.\n";
if(!(socket_bind($sock, $address, $port))){
$errorCode = socket_last_error();
$errorMsg = socket_strerror($errorCode);
die("socket_bind() failed -> {$errorCode}:{$errorMsg}\n");
}
echo "Server opened on {$address}:{$port}\n";
if(!(socket_listen($sock, $maxConnections))){
$errorCode = socket_last_error();
$errorMsg = socket_strerror($errorCode);
die("socket_listen() failed -> {$errorCode}:{$errorMsg}\n");
}
echo "Waiting for connections...\n";
$client = socket_accept($sock);
if(socket_getpeername($client, $address, $port)){
echo "The client {$address}:{$port} is online.\n";
}
$msg = socket_read($client, 1024000);
if(!(socket_write($client, $msg, strlen($msg)))){
$errorCode = socket_last_error();
$errorMsg = socket_strerror($errorCode);
die("socket_write() failed -> {$errorCode}:{$errorMsg}\n");
}
echo "Message sent\n";
socket_close($client);
socket_close($sock);
?>
I ran this php file with xampp shell using the following expression:
php htdocs/server.php
and I got this message on shell:
php htdocs/server.php
Server created.
Server opened on 127.0.0.1:1777
Waiting for connections...
Then I opened my client.html on chrome (my supports websockets).
My client.html code is:
<html>
<head>
<meta charset="UTF-8" />
<title>Websockets web-server connection</title>
</head>
<body>
<p>Websockets connection. Status: <span id="status"></span></p>
<script type="text/javascript">
var webSockets = new WebSocket("ws://127.0.0.1:1777/");
webSockets.onopen = function(){
document.getElementById("status").innerHTML="connected";
webSockets.send("ping");
}
</script>
</body>
</html>
And I received this message on javascript console log:
WebSocket connection to 'ws://127.0.0.1:1777/' failed: client.html:9
And my shell had this messages:
php htdocs/server.php
Server created.
Server opened on 127.0.0.1:1777
Waiting for connections...
The client 127.0.0.1:64446 is online
Message sent
However I didn't receive any message on client, I do not even get a connected status.
What is happening? Where is my error?
Thank you.
WebSockets are not raw TCP sockets. They require a rather complex HTTP-like handshake to establish a connection, and require data transferred over them to be encoded and framed in a very particular way. The protocol is defined in RFC 6455.
Unless you are feeling incredibly masochistic, you don't want to try to implement this yourself. Use a library like Ratchet to implement WebSockets in PHP.
I had the same problem bro but no need of using Ratchet or other libraries you can write your own simple code . The handshake process,and the masking-unmasking of messages is rather difficult so i copied the code for those
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/\r\n".
"Sec-WebSocket-Accept:$secAccept\r\n\r\n";
socket_write($client_conn,$upgrade,strlen($upgrade));
return $upgrade;
}
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;
}
Instead of socket_accept user socket_read to get the http header containing request from webpage that it wants to upgrade its http conn to websocket then use the handshake function above to write an accept header message .then your connection will be established .but still on the client side you have to add events like these
if("WebSocket" in window){
var a = "ws://"+serverip+":9000";
var ws = new WebSocket(a);
var error = null;
ws.onopen = function(){
open();
}
ws.onerror = function(err){
errorhandler(err);
}
ws.onmessage = function(e){
messagehandler(e);
}
ws.onclose = function(){
close();
}
}
function open(){
document.getElementById('logs').innerHTML+='<p>WebSocket Connection OPened</p>';
}
function errorhandler(err){
document.getElementById('logs').innerHTML+='<p>WebSocket Connection Error occured &nbsp'+err.data+'</p>';
}
function messagehandler(a){
document.getElementById('logs').innerHTML+="<p>"+a.data+"</p>";
}
function close(){
document.getElementById('logs').innerHTML+='<p>WebSocket Connection Closed</p>';
ws = null;
}

Categories

Resources