Websocket connection to colyseus by hand: no messages - javascript

I'm trying to connect by hand to Colyseus. I am trying now with node but I don't understand why I can't get past the first message.
Here is the code:
var WebSocket = require('ws');
var XMLHttpRequest = require('xhr2');
var xhr = new XMLHttpRequest()
var myurl = "http://localhost:2567/matchmake/joinOrCreate/my_room"
var res = '';
var socket = '';
let data = `{ "Id": 123}`;
xhr.open("POST", myurl);
xhr.setRequestHeader("Accept", "application/json");
xhr.setRequestHeader("Content-Type", "application/json");
xhr.onreadystatechange = function () {
if (xhr.readyState === 4) {
console.log(xhr.status);
console.log(xhr.responseText);
res = JSON.parse(xhr.responseText);
var processId = res['room']['processId'];
var roomId = res['room']['roomId'];
var sessionId = res['sessionId'];
var wsurl = "ws://localhost:2567/"+processId+"/"+roomId+"?sessionId="+sessionId;
socket = new WebSocket(wsurl);
socket.onmessage = (event) => {
console.log('Message from server ', event.data);
};
}
};
xhr.send(data);
I can see the first message, but when I "broadcast" a message by changing something on the server state, nothing appears. If I connect with the official library, I do see messages going back and forth.
Am I missing something?

Related

How to get values from JSON XMLHttpRequest?

I am new to web development, and I am using a XMLHttpRequest() in JavaScript to get data from an api. I am trying to create variables from the data but am getting an error when I try to do the following. Does anyone know what is wrong with the line var data1 = data["data1"];?
<script>
const Http = new XMLHttpRequest();
const url = "www.mytestapi.com/response.json";
Http.open("GET", url);
Http.send();
Http.onreadystatechange = (e) => {
var json = JSON.parse(Http.responseText)
var data = json.Data
var data1 = data["data1"]; //issue caused here
}
<script>
you don't need to parse response data, data is parsed already , try this
const xhr = new XMLHttpRequest();
const url = "www.mytestapi.com/response.json";
xhr.open('GET', url);
xhr.responseType = 'json';
xhr.onload = () => {
console.log("load - "+ JSON.stringify(xhr.response));
var data = xhr.response;
var data1 = data["data1"]
}
xhr.onerror = () => {
console.log("error status - " + xhr.status);
}
xhr.send()

Javascript GET request after POST request

I have a page that uses a function for getting some data, with a GET xhttp request, from a database (get_worktime_list()).
On the same page, I can add some data to the database with a form using a POST xhttp request and after a success (saved in the response) I will get the content included the new line from the database with the same function get_worktime_list().
The problem is that when getworktime is called after the POST request, get_worktime_list() makes another POST request instead of a GET. why???
function http_request(post_data, end_point, type)
{
console.log("HTTP");
var res = 0;
//var data = "data=0&username="+stored_token.username+"&token="+stored_token.token;
var data = "data=0&"+post_data;
console.log(data);
// Check if is valid token/username from database
const url = "http://192.168.1.188:5000/services/"+end_point;
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
res = JSON.parse(xhttp.responseText);
}
};
if (type == "GET")
{
console.log(url+"?"+post_data);
xhttp.open("GET", url+"?"+post_data, false);
}
else
{
console.log("Data: "+data);
xhttp.open("POST", url, false);
}
xhttp.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
xhttp.send(data);
xhttp.abort();
return res;
}
This add data to DB
function addworktime(username,token)
{
console.log("Aggiungo ore");
var date = document.getElementById("data").value;
var type = document.getElementById("turno").value;
var pay = document.getElementById("paga").value;
var emp = document.getElementById("dipendente").value;
var ore = document.getElementById("num_ore").value;
var data = "username="+username+"&token="+token+"&day="+date+"&turn_type="+type+"&pay="+pay+"&emp="+emp+"&ore="+ore;
var res = http_request(data,"admin/dipendenti/addtime.php","");
//console.log(res);
if (res.insert_ok == 1)
{
display_time_table(0,0,null);
} else {
console.log(res);
}
}
This function makes a GET request when a page load and a POST request when called by addworktime()
function display_time_table(from,to,cf)
{
let time_list_table = document.getElementById("list-container");
var time_list = get_worktime_list(saved_data.username,saved_data.token,from,to,cf);
let time_table = generate_time_list_table(time_list);
time_list_table.innerHTML = time_table;
}
function get_worktime_list(username,token,date_from,date_to,cf)
{
var data = "username="+username+"&token="+token;
if (cf != "" || cf != null)
{
data = data+ "&dipendente="+cf;
}
if (date_from != 0)
{
data = data +"&date_from="+date_from;
}
if (date_to != 0)
{
data = data + "&date_end="+date_to;
}
var time_list = http_request(data,"admin/dipendenti/getworktime.php", "GET");
return time_list;
}
The server can only accept GET requests for that API and obviously, I get a parse error parsing the JSON response.
Thanks for help

How to get rid of «POST net::ERR_CONNECTION_RESET» error?

I am making a chat on php Ratchet and I have difficulties with push tutorial
I am sending user message to send_message.php and there is a mistake: "POST work-fox/send_message.php net::ERR_CONNECTION_RESET".
chat.js:
var panel = document.querySelector('.panel');
var message = document.querySelector('.message');
var start_dialog = document.querySelector('#start_dialog');
var send_msg = document.querySelector('#send_msg');
var chatId = '1';
var conn = new ab.Session('ws://localhost:8443',
function() {
conn.subscribe(chatId, function(topic, data) {
console.log(data);
});
},
function() {
console.warn('WebSocket connection closed');
},
{'skipSubprotocolCheck': true}
);
send_msg.onclick = function(e) {
e.preventDefault();
var xhr = new XMLHttpRequest();
var form = new FormData();
form.append('message', message.value);
xhr.open("POST", "send_message.php", true);
xhr.send(form);
xhr.onload = function(e) {
console.log(this.responseText);
}
}
send_message.php:
$entryData = array(
'fromId' => '1',
'message' => $_POST['message'],
'toId' => '2'
);
$context = new ZMQContext();
$socket = $context->getSocket(ZMQ::SOCKET_PUSH, 'my pusher');
$socket->connect("tcp://localhost:5555");
$socket->send(json_encode($entryData));
The error, as I understand it, lies in this line: $socket = $context->getSocket(ZMQ::SOCKET_PUSH, 'my pusher')
Please tell me how to solve my problem

Chrome crashes when use XHR to send large file

I use XMLHttpRequest to send POST data to nodejs (expressjs api). The size of file about 200mb. When I do, Chrome crashes, but the Firefox doesn't. Does Chrome have a limited file size?
And how can I upload the large file via JavaScript?
This is my code send xhr request:
// create http request API AI Engine
var xhr = new XMLHttpRequest();
xhr.open('POST', url, true);
xhr.responseType = 'arraybuffer';
xhr.timeout = 3600000;
xhr.onload = function() {
// reponse measage
if (this.status === 200) {
var errorArea = document.getElementById('error-area');
errorArea.style.display = 'none';
zip.files = {};
// unzip File
zip.loadAsync(this.response)
.then(function(zip) {
// will be called, even if content is corrupted
for (const file in zip.files) {
if (zip.files.hasOwnProperty(file)) {
const fileObject = zip.files[file];
fileObject.async('arraybuffer').then(function(fileData) {
var fileSave = new Blob([new Uint8Array(
fileData)]);
// Save file
saveAs(fileSave, fileObject.name);
})
}
}
}, function(e) {
var errorArea = document.getElementById('error-area');
errorArea.style.display = 'block';
errorArea.innerHTML =
'<strong>Error</strong> Cant not unzip file return.';
});
// get response stream data
} else {
var errorArea = document.getElementById('error-area');
errorArea.style.display = 'block';
errorArea.innerHTML =
'<strong>Error</strong> Cant not analyze file: ' + this.statusText;
}
};
// Handle when have error with xhr, show message
xhr.onerror = function(err) {
var errorArea = document.getElementById('error-area');
errorArea.style.display = 'block';
errorArea.innerHTML =
'<strong>Error</strong> Cant not analyze file: ' + this.statusText;
};
// Handle when have timeout with xhr, show message
xhr.ontimeout = function() {
var errorArea = document.getElementById('error-area');
errorArea.style.display = 'block';
errorArea.innerHTML =
'<strong>Error</strong> Cant not analyze file: Request time out';
};
// Add custom header
xhr.setRequestHeader('Content-type', 'application/octet-stream');
xhr.setRequestHeader('file-name', Date.now().toString() + '.zip');
xhr.setRequestHeader('file-length', data.byteLength);
// Send arraybuffer to server
xhr.send(data);
});

Dynamics CRM 2016: JavaScript causes JSON Parse Error

I am trying to get the price of a product in Dynamics CRM 2016, by javascript on the onChange event for the product. This is on a custom entity I have created and is using the pricelistid and the productid.
When I use the same javascript in the console on Chrome i can get the data out but when it is executed by the CRM form I get an error:
SyntaxError: Unexpected end of JSON input at JSON.parse ()
The code is:
var pricelevelid = Xrm.Page.getAttribute("sg_pricelistid").getValue()[0].id;
pricelevelid = pricelevelid.replace(/[{}]/g, "");
var productdata = Xrm.Page.getAttribute("sg_productid").getValue();
if (productdata != null)
{
console.log("going into productdata loop");
productid = productdata[0].id;
productid = productid.replace(/[{}]/g, "");
var req = new XMLHttpRequest();
req.open("GET", Xrm.Page.context.getClientUrl() + "/api/data/v8.0/productpricelevels?$select=amount,_pricelevelid_value,_productid_value,productpricelevelid&$filter=_pricelevelid_value eq " + pricelevelid + " and _productid_value eq " + productid + "", true);
req.setRequestHeader("OData-MaxVersion", "4.0");
req.setRequestHeader("OData-Version", "4.0");
req.setRequestHeader("Accept", "application/json");
req.setRequestHeader("Content-Type", "application/json; charset=utf-8");
req.onreadystatechange = function() {
if (this.readyState === 4) {
req.onreadystatechange = null;
if (this.status === 200) {
var results = JSON.parse(this.response);
for (var i = 0; i < results.value.length; i++) {
var amount = results.value[i]["amount"];
var amount_formatted = results.value[i]["amount#OData.Community.Display.V1.FormattedValue"];
}
} else {
Xrm.Utility.alertDialog(this.statusText);
}
}
};
req.send();
data = JSON.parse(req.responseText);
var amount = data.value[0]["amount"];
Xrm.Page.getAttribute("sg_unitprice").setValue(amount);
}
You are performing an asynchronous request and then attempting to parse the response, before it has been set to anything.
This happens at the bottom of your code block at data = JSON.parse(req.responseText), right after you send the request.
All code that relies on the response should be executed in the req.onreadystatechange callback function.

Categories