PHP: Can't connect to francium diffsocket - phpwebsocket

I am developing a simple group chat using websocket on xampp 7.0.9, in windows. Here is my code:
run-server.php
<?php
require_once __DIR__ . "/vendor/autoload.php";
$DS = new Fr\DiffSocket(array(
"server" => array(
"host" => "127.0.0.1",
"port" => "8000"
)
));
$DS->addService("hello", __DIR__ . "/Hello.php");
$DS->run();
index.php
<html>
<body>
<script src="http://lab.subinsb.com/projects/jquery/core/jquery-2.1.1.js"></script>
<script>
$(document).ready(function(){
window.ws = new WebSocket("ws://127.0.0.1:8000/?service=hello");
});
</script>
</body>
Hello.php
<?php
namespace Fr\DiffSocket\Service;
use Ratchet\MessageComponentInterface;
use Ratchet\ConnectionInterface;
class Hello implements MessageComponentInterface {
public function onOpen(ConnectionInterface $conn){
echo "New Connection - " . $conn->resourceId;
}
public function onClose(ConnectionInterface $conn){}
public function onError(ConnectionInterface $conn, $error){}
public function onMessage(ConnectionInterface $conn, $message){
$conn->send("Hello");
}
}
?>
run-server.php starts well, but when I connect by running index.php, I get the following JavaScript error:
(index):6 WebSocket connection to 'ws://127.0.0.1:8000/?service=hello' failed: Connection closed before receiving a handshake response
And this in the run-server.php
Server started on 127.0.0.1:8000
Notice: Undefined property: stdClass::$request in E:\Projects\Installed\xmpp\htdocs\soc\server\vendor\francium\diffsocket\src\DiffSocket\Server.php on line 80
Fatal error: Uncaught Error: Call to a member function getQuery() on null in E:\Projects\Installed\xmpp\htdocs\soc\server\vendor\francium\diffsocket\src\DiffSocket\Server.php:80 Stack trace: #0 E:\Projects\Installed\xmpp\htdocs\soc\server\vendor\francium\diffsocket\src\DiffSocket\Server.php(25): Fr\DiffSocket\Server->getService(Object(Ratchet\WebSocket\WsConnection)) #1 E:\Projects\Installed\xmpp\htdocs\soc\server\vendor\cboden\ratchet\src\Ratchet\WebSocket\WsServer.php(142): Fr\DiffSocket\Server->onOpen(Object(Ratchet\WebSocket\WsConnection)) #2 E:\Projects\Installed\xmpp\htdocs\soc\server\vendor\cboden\ratchet\src\Ratchet\Http\HttpServer.php(51): Ratchet\WebSocket\WsServer->onOpen(Object(Ratchet\Server\IoConnection), Object(GuzzleHttp\Psr7\Request)) #3 E:\Projects\Installed\xmpp\htdocs\soc\server\vendor\cboden\ratchet\src\Ratchet\Server\IoServer.php(112): Ratchet\Http\HttpServer->onMessage(Object(Ratchet\Server\IoConnection), 'GET /?service=h...') #4 E:\Projects\Installed\xmpp\htdocs\soc\server\vendor\cboden\ratchet\src in E:\Projects\Installed\xmpp\htdocs\soc\server\vendor\francium\diffsocket\src\DiffSocket\Server.php on line 80
Can anyone help please. Thanks.

Related

Defining a property via process.env in javascript

I'm new to JavaScript and stuck.
I'm writing my first "real" Electron App and want to connect via sftp. (ssh2-sftp-client to be more specific)
When I set up the connection like the example:
sftp.connect({
host: '192.168.76.173',
port: '22',
username: 'Backup',
password: 'PasswordInPlainText'
}).then(() => {
return sftp.list('/Backups/Server');
}).then(data => {
console.log(data, 'the data info');
}).catch(err => {
console.log(err, 'catch error');
});
everything works like a charm. But when I try to "hide" my credentials in an .env file:
sftp.connect({
host: process.env.HOST,
port: process.env.PORT,
username: process.env.USERNAME,
password: process.env.PASSWORD
}).then(() => {
return sftp.list('/Backups/Server');
}).then(data => {
console.log(data, 'the data info');
}).catch(err => {
console.log(err, 'catch error');
});
I get the error message:
Error: connect: getConnection: All configured authentication methods failed
I checked via
console.log("Host to connect: "+ process.env.HOST)
and the correct output is:
Host to connect: 192.168.76.173
The content of the .env File is
HOST='192.168.76.173'
PORT='22'
USERNAME='Backup'
PASSWORD='PasswordInPlainText'
So this my first time working with environment Variables at all, so I'm guessing I misunderstood something, or a JavaScript property can't be defined by a string this way.
Your problem is that the .env files are not supported in NodeJS by default and you might have some env variables already with the same names and different values (defined in the system probably).
You could either use a NPM package like dotenv or parse the contents of the file by yourself.
You could also test it like that:
// Place this code before you use the ENV variables.
// Replace the `<variables>` with the real data
// and test if your code works with the ENV variables.
process.env.HOST = '<your host ip>';
process.env.PORT = '<your port>';
process.env.USERNAME = '<username>';
process.env.PASSWORD = '<password>';

Error when connecting to #discord/voice API from Digitalocean droplet

I have deployed a Node.js app as a Web Application in Digitalocean using the standard build & deploy process. Within this app I'm attempting to connect to the Discord Voice API (#discord/voice)
Code
const { createAudioPlayer, createAudioResource ... } = require('#discordjs/voice');
player = createAudioPlayer({
behaviors: {
noSubscriber: NoSubscriberBehavior.Pause
}
});
...
let resource = createAudioResource(source.stream, {
inputType: source.type
});
player.play(resource);
const connection = joinVoiceChannel({
guildId: guild.id,
channelId: channel.id,
adapterCreator: guild.voiceAdapterCreator
})
connection.subscribe(player);
Error
/workspace/node_modules/#discordjs/voice/dist/index.js:353
this.socket.once("close", () => reject(new Error("Cannot perform IP discovery - socket closed")));
^
Error: Cannot perform IP discovery - socket closed
at Socket.<anonymous> (/workspace/node_modules/#discordjs/voice/dist/index.js:353:46)
at Object.onceWrapper (node:events:641:28)
at Socket.emit (node:events:539:35)
at socketCloseNT (node:dgram:746:8)
at processTicksAndRejections (node:internal/process/task_queues:82:21)
Emitted 'error' event on VoiceConnection instance at:
at VoiceConnection2.onNetworkingError (/workspace/node_modules/#discordjs/voice/dist/index.js:1531:10)
at Networking.emit (node:events:527:28)
at /workspace/node_modules/#discordjs/voice/dist/index.js:689:32
at runMicrotasks (<anonymous>)
at processTicksAndRejections (node:internal/process/task_queues:96:5)
I think this is a problem with port forwarding or NAT between the host and the container, does anyone know how to resolve?

How to connect to a docker container from web?

I am working on a new project where I need to connect to a docker container from web?
By connect I mean I will create a shell in the website and tat shell will be able to connect to the running container.
I am not able to figure out how to proceed with the project.
Can anyone help me out?
From what I know there is no out of the box solution, you should make your own api executing command on your container running docker exec <id> <command> and returning the output, mind escape the command.
However you should know that letting a user run commands inside a docker is dangerous as it could impact your host.
You should be able to use Docker APIs for this (https://docs.docker.com/engine/api/) along with a framework that wraps the APIs. For example refer dockerode.
You could combine some JavaScript modules. node-pty and xterm being the most important. Additionally, ws is useful, but could be replaced but something else.
Note: this is not a production ready example. In particular, you should take care of safety measurements, or better yet, let no one but yourself use it.
server.js
import { WebSocketServer, createWebSocketStream } from 'ws';
import pty from 'node-pty';
const wss = new WebSocketServer({ port: 3000 });
wss.on('connection', (ws) => {
console.log('new connection');
const duplex = createWebSocketStream(ws, { encoding: 'utf8' });
const proc = pty.spawn('docker', ['run', "--rm", "-ti", "ubuntu", "bash"], {
name: 'xterm-color',
});
const onData = proc.onData((data) => duplex.write(data));
const exit = proc.onExit(() => {
console.log("process exited");
onData.dispose();
exit.dispose();
});
duplex.on('data', (data) => proc.write(data.toString()));
ws.on('close', function () {
console.log('stream closed');
proc.kill();
duplex.destroy();
});
});
index.html
<!doctype html>
<html>
<head>
<link rel="stylesheet" href="node_modules/xterm/css/xterm.css" />
<script src="node_modules/xterm/lib/xterm.js"></script>
</head>
<body>
<div id="terminal"></div>
<script type="module">
const term = new Terminal();
term.open(document.getElementById('terminal'));
const ws = new WebSocket('ws://localhost:3000');
ws.onmessage = async ({ data }) => term.write(await data.text());
term.onData((data) => ws.send(data));
</script>
</body>
</html>
Note: I am using the statics from the node modules folder, in your real code you probably want to use a bundler for this.
I am serving the entire project with nginx on port 8080 for simplicity. And then I start the server with node.
docker run -d --rm -p 8080:8080 -v "$PWD:/usr/share/nginx/html" nginxinc/nginx-unprivileged
node server.mjs
Afterwards, I can open http://localhost:8080 in my browser, and get a shell.
The dependencies in my package.json are these:
"dependencies": {
"node-pty": "^0.10.1",
"ws": "^8.7.0",
"xterm": "^4.18.0"
}
You can view the code in this repo: https://github.com/bluebrown/web-shell.

Exception when connecting to Database through Dart

I was trying to connect to MySQL database in Flutter application using sqljocky5 using the below code using dart language
void getInfo () async {
var pool = new ConnectionPool(
host: 'localhost',
port: 3305,
user: 'root',
password: 'mysql',
db: 'smartlender',
max :5
);
print('test');
var results = await pool.query('SELECT employee.firstName FROM smartlender.employee;'); // exception is thrown here
results.forEach((row){ // for each loop to add data to the list created above
names.add(row[0].toString());
});
Then I received this exception:
I have working connection to MySQL database and the query is exiting without an error .
I appreciate a lot if someone could resolve this issue .
Isn't it default Mysql port number 3306?

React Native Socket.io How to Connect to Local Node Server from Device

I'm making a connection when pointing the io.connect() method towards my localhost in the iOS simulator, so everything is working there.
But when the connect() method is pointed towards my machine's LAN IP address I am unable to successfully connect to the server neither in the simulator or on the device..
I'm pretty stumped on this one right now, any help would be appreciated thanks.
Solved by tunneling localhost:3000 via ngrok and allowing an exception domain.
In your info.plist you need the following under App Transport Security Settings
On a mac command line run
brew cask install ngrok
ngrok http 3000
Then grab the outputted ngrok.io URL and use it in your io.connect() call and you should be set.
Simple way -> Connection with Socket.io to Local Node Server:
First Step : you need to install socket.io into your project -
npm install socket.io-client
or
yarn add socket.io-client
App.js file :
import { io } from "socket.io-client";
const socketIOConnectionWithLocalhost = () => {
var socket = io('localhost:3000', { jsonp: false });
console.log('socket: ', socket);
socket.on('connect', () => {
console.log("socket connected...");
})
socket.on("update", () => {
console.log('App.js : socket event recieved:');
});
};
Second Step : create server folder and inside it create two files: app.js and index.html (As per given in below image)
Server/app.js File :
var express = require('express');
var app = express();
const server = require('http').createServer(app);
const io = require('socket.io')(server);
io.on('connection', (socket) => {
console.log('server - app.js - socket.id: ', socket.id);
socket.on('update', (data) => {
console.log('server - app.js - update:', data);
io.emit('update', socket.id)
});
});
app.get('/', function (req, res) {
res.sendFile(__dirname + '/index.html');
});
server.listen(3000);
index.html file :
<h1>Welcome To Server</h1>
<button>UPDATE</button>
<script src="/socket.io/socket.io.js"> </script>
<script>
var socket = io();
var button = document.querySelector('button');
button.onclick = function(){
console.log('index.html - buttion click...')
socket.emit('update');
}
</script>
Third Step : To start node server using below command:
first go to inside server folder then enter below command -> cd Server
node app.js
Then open any browser and hit localhost url -> http://localhost:3000/
Thanks..!

Resources