Manage Rcon remote web rust server - javascript

I am trying to develop a web application that allows me to type commands in the Rcon console via the web Browser.
The problem is that every time I send a command I get “[Rcon] Failed to parse message, incorrect format”.
Error message rcon
File log server
Code:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>WebSocket</title>
</head>
<body>
<h1>WebSockets Rust Server</h1>
<input type="button" value="Send" onclick="webSocketTest();">
<script>
function webSocketTest() {
// Create the WebSocket
const rcon = new WebSocket('ws://localhost:28016/1234');
rcon.onopen = function(e) {
// This line causes the problem
rcon.send('status');
}
rcon.onmessage = function(e) {
// Code
}
rcon.onerror = function(e) {
// Code
}
rcon.onclose = function(e) {
// Code
}
}
</script>
</body>
</html>
EDIT:
Finally I fix the problem. I was making the mistake of trying to collect the data in the wrong function.
<<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>WebSocket</title>
</head>
<body>
<h1>WebSockets Rust Server</h1>
<input type="button" value="Send" id="btnSend"><br>
<textarea id="response" rows="10" cols="60"></textarea>
<script>
const rcon = new WebSocket('ws://localhost:28016/1234');
console.log(rcon);
rcon.onopen = function() {
console.log('Connected');
};
/* In this funcion have the server response */
rcon.onmessage = function(e) {
const msg = JSON.parse(e.data);
document.getElementById('response').innerHTML = msg.Message;
}
rcon.onerror = function (e) {
console.log(e);
}
rcon.onclose = function(e) {
console.log('Connection closed');
console.log(e);
};
/* Click Event on send btn that calls anonymous function to send the data */
const btnSend = document.getElementById("btnSend");
btnSend.addEventListener('click', function() {
/* Data to send */
const data = {
Message: "status", // rcon command
Identifier: 1, // +server.identity
Name: "totalgamer" // +server.hostname
};
/* Need to use JSON.stringify before send the data */
rcon.send(JSON.stringify(data));
});
</script>
</body>
</html>
Now it's works fine.

Related

add participant for the twilio room

Twilio Room was created using the below code, but not able to produce any output, it is showing everything is working fine, but not able to know how can i proceed forward so I can add multiple participants and can make a video call for each other. it asks for the camera and mike permission but not able to see the video. thanks in advance if you see any mistake please ignore it
require_once ./vendor/autoload.php;
use Twilio\Rest\Client;
// use Twilio\TwiML\VoiceResponse;
// Find your Account SID and Auth Token at twilio.com/console
// and set the environment variables. See http://twil.io/secure
$sid = "AC3c0f477f066042308c088574dae7bf9a";
$token = "8c7e575ac24e6e6f924bbaa22c42bbb4";
$twilio = new Client($sid, $token);
$room = $twilio->video->v1->rooms
->create([
"statusCallback" => "http://example.org",
"type" => "peer-to-peer",
"uniqueName" => "DailyStandup227"
]
);
print_r($room);
*After this I generated the access token
<?php
// Get the PHP helper library from https://twilio.com/docs/libraries/php
require_once './vendor/autoload.php';// Loads the library
use Twilio\Jwt\AccessToken;
use Twilio\Jwt\Grants\ChatGrant;
use Twilio\Jwt\Grants\VideoGrant;
// Required for all Twilio access tokens
$twilioAccountSid = 'AC3c0f477f066042308c088574dae7bf9a';
$twilioApiKey = 'SKb30ca8d445b8bd68479c54c2544fa1b4';
$twilioApiSecret = 'ixmFdysnjHRuXgXCTOQwl4I4OIsPa27l';
// Required for Chat grant
$roomName = 'DailyStandup221';
// choose a random username for the connecting user
$identity = "amirIshaque";
// Create an access token, which we will serialize and send to the client
$token = new AccessToken(
$twilioAccountSid,
$twilioApiKey,
$twilioApiSecret,
3600,
$identity
);
// Create Voice grant
$videoGrant = new VideoGrant();
$videoGrant->setRoom($roomName);
// Add grant to token
$token->addGrant($videoGrant);
// render token to string
echo $token->toJWT();
** then by using the above access token and room **
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>My Website</title>
<!-- <link rel="stylesheet" href="./style.css"> -->
<!-- <link rel="icon" href="./favicon.ico" type="image/x-icon"> -->
</head>
<body>
<main>
<h1>Welcome to My Website</h1>
<div id="container"></div>
<Response>
<Dial><Conference>DailyStandup18</Conference></Dial>
<Response>
</main>
<!-- <script src="./twilio-video.min.js"></script> -->
<script src="./twilio-video.min.js"></script>
<script>
const Video = Twilio.Video;
console.log('$TOKEN',Video);
Video.connect('eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiIsImN0eSI6InR3aWxpby1mcGE7dj0xIn0.eyJqdGkiOiJTS2IzMGNhOGQ0NDViOGJkNjg0NzljNTRjMjU0NGZhMWI0LTE2NjY0NDcyMDMiLCJpc3MiOiJTS2IzMGNhOGQ0NDViOGJkNjg0NzljNTRjMjU0NGZhMWI0Iiwic3ViIjoiQUMzYzBmNDc3ZjA2NjA0MjMwOGMwODg1NzRkYWU3YmY5YSIsImV4cCI6MTY2NjQ1MDgwMywiZ3JhbnRzIjp7ImlkZW50aXR5IjoiYW1pcklzaGFxdWUiLCJ2aWRlbyI6eyJyb29tIjoiRGFpbHlTdGFuZHVwMjIxIn19fQ.f-yld_8HU_HX6f1NVuwxSOIq3KEcuh6sWWhms6bar14', { name: 'DailyStandup227' }).then(room => {
console.log(room);
console.log('Connected to Room "%s"', room.name);
console.log(room.participants);
room.participants.forEach(participantConnected);
room.on('participantConnected', participantConnected);
room.on('participantDisconnected', participantDisconnected);
room.once('disconnected', error => room.participants.forEach(participantDisconnected));
alert('5');
});
// Twilio.Video
// .createLocalVideoTrack()
// .then(track => {
// const container = document.getElementById('container');
// container.appendChild(track.attach());
// });
function participantConnected(participant) {
console.log('Participant "%s" connected', participant.identity);
alert('1');
const div = document.createElement('div');
div.id = participant.sid;
div.innerText = participant.identity;
participant.on('trackSubscribed', track => trackSubscribed(div, track));
participant.on('trackUnsubscribed', trackUnsubscribed);
participant.tracks.forEach(publication => {
if (publication.isSubscribed) {
trackSubscribed(div, publication.track);
}
});
document.body.appendChild(div);
}
function participantDisconnected(participant) {
alert('2');
console.log('Participant "%s" disconnected', participant.identity);
document.getElementById(participant.sid).remove();
}
function trackSubscribed(div, track) {
alert('3');
div.appendChild(track.attach());
}
function trackUnsubscribed(track) {
alert('4');
track.detach().forEach(element => element.remove());
}
</script>
<!-- <script src="index.js"></script> -->
</body>
</html>

Why does httpr.send() always fail?

I had similar code run before but now i've lost it. No matter what I do, it will never run the php code.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<script>
function kosarica() {
var vrednost = "Itworks!";
var httpr=new XMLHttpRequest();
httpr.open("POST","izpis3.php",true);
httpr.setRequestHeader("Content-type","aplication/x-www-form-urlencode");
httpr.onreadystatechange=function(){
if(httpr.readyState==4 && httpr.status ==200){
document.getElementById("responce").innerHTML=httpr.responseText;
}
httpr.send("vrednost"+vrednost);
}
}
</script>
</head>
<body>
<p id="responce">a</p>
<button onclick="kosarica()">Click me</button>
</body>
</html>
PHP Code:
<?php
echo $_POST['vrednost'];
?>
I know that I can make code for this example all in javascript but I want to run more php code where it access my database.
It does not fail, but it does never happen. You need to move the send() outside the handler.
The content type is wrong.
You need to use an equal sign to make it a variable for PHP.
Please do not use var keyword. Use const for a constant or let for a variable.
function kosarica() {
const vrednost = "Itworks!";
const httpr = new XMLHttpRequest();
httpr.open("POST", "izpis3.php", true);
httpr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
httpr.onreadystatechange = function () {
if (httpr.readyState === 4 && httpr.status === 200) {
document.getElementById("responce").innerHTML = httpr.responseText;
}
}
httpr.send("vrednost=" + vrednost);
}

Deserialize data from websocket response

I'm am trying to deserialize a WebSocket response with the package msgpacket.
When trying to deserialize the packet response I am getting the error:
Uncaught Error: Invalid argument: The byte array to deserialize is empty.
Here is a basic snippet showing this. I am using echo.websocket.org to test this. It sends back the same response it gets.
this.socket = new WebSocket('wss://echo.websocket.org');
this.socket.onopen = () => {
console.log('connected');
var sourceData = {
hello: 1,
world: "test"
};
var data = msgpack.serialize(sourceData);
this.socket.send(data.buffer);
var after = msgpack.deserialize(data.buffer);
console.log(after);
}
this.socket.onmessage = function (event) {
var data = msgpack.deserialize(new Uint8Array(event.data));
console.log(data);
};
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<body>
<script src="https://raw.githack.com/ygoe/msgpack.js/master/msgpack.min.js"></script>
</body>
</html>
I am simply trying to retrieve the data after receiving the WebSocket response.
I was able to solve the problem.
I figured out I needed to convert a blob into an array buffer
This is what worked
var blob = event.data;
var arrayBuffer = null;
arrayBuffer = await new Response(blob).arrayBuffer();
var data = msgpack.deserialize(arrayBuffer);
console.log(data);
Found here: https://stackoverflow.com/a/55204517/10997917

txt file wont load by using vanilla javascript

I am trying to implement an ajax with simple txt file but the file won't load any suggestion
the html:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<script src="app.js"></script>
<title>Ajax 1 - Text File</title>
</head>
<body>
<button id="button" onclick="loadText()">Get Text File</button>
</body>
</html>
and the javascript file:
//Create event Listener of the Get Text File
function loadText(){
// Create XHR object
var xhr = new XMLHttpRequest();
// OPEN - type, url/fileName, async
//console.log(xhr);
xhr.open('GET', 'sample.txt', true);
xhr.onload = function(){
//HTTP statuses
//200: OK
//403: Forbiden
//404: Not Found
if(this.status == 200){
console.log(this.responseText);
}
//Send Request
xhr.send();
}
}
and this is the sample.txt file
This massage form the text file just to ensure you have the ability to
access the text file. so if you do good for you otherwise just keep
trying
Note, I'm trying to achieve it using vanilla javascript without any frameworks or library
As an output I get nothing once I click the button and even in the network tab in the inspector the txt file never even load.
Note, I'm using live sever on vscode
xhr.send() should be outside xhr.onload()
xhr.onload() is the callback function to be executed when the request completes successfully.
refer the docs here https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequestEventTarget/onload
and the javascript file:
//Create event Listener of the Get Text File
function loadText(){
// Create XHR object
var xhr = new XMLHttpRequest();
// OPEN - type, url/fileName, async
//console.log(xhr);
xhr.open('GET', 'sample.txt', true);
xhr.onload = function(){
//HTTP statuses
//200: OK
//403: Forbiden
//404: Not Found
if(this.status == 200){
console.log(this.responseText);
}
//Send Request
}
xhr.send();
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<script src="app.js"></script>
<title>Ajax 1 - Text File</title>
</head>
<body>
<button id="button" onclick="loadText()">Get Text File</button>
</body>
</html>

podio API javascript

I m trying to connect Podio API with a webpage.
I have this error : "podio.hasAuthError is not a function", but i don t know what to do....
I show you my (basic) code.
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<script type="text/javascript" src="lib/podio-js/dist/podio-js.js"></script>
<script type="text/javascript">
var podio = new PodioJS({ authType: 'client', clientId: 'foo'});
var redirectURL = 'http://foo';
// isAuthenticated either gets the cached accessToken
// or will check whether it is present in the hash fragment
podio.isAuthenticated().then(function(){
// ready to make API calls...
}).catch(function(){
if (podio.hasAuthError()) {
console.log(podio.getAuthError());
} else {
// start authentication via link or redirect
console.log(platform.getAuthorizationURL(redirectURL));
}
});
</script>
</head>
<body>
</body>
</html>

Categories