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
Related
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?
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()
I have trying work around Server Sent Events. I have to push event from different server and on user response.
I have consumer on localhost:A and server on localhost:B
What i want to do is push event only when i click on Push Event Button.
and establish the persistent connection through event channel.
localhostA js
function contentLoaded() {
var source = new EventSource('https://localhost:44398/home/message', {
withCredentials: true
});
//var ul = $("#messages");
source.onmessage = function (e) {
var li = document.createElement("li");
var returnedItem = e.data;
li.textContent = returnedItem;
$("#messages").append(li);
}
source.onerror = function (e) {
console.log(e);
}
};
localhostB Server Action Method
public IActionResult Message(int id = 0)
{
var result = string.Empty;
var sb = new StringBuilder();
sb.AppendFormat("retry: 10000\n\n");
sb.AppendFormat("data: {0} {1}\n\n", "hello",id);
Response.Headers.Add("Connection", "keep-alive");
var a = Response.HttpContext.Connection.Id;
return Content(sb.ToString(), "text/event-stream");
}
localhostB client side
<button onclick="javascript:sendEvent()">Push Event</button>
localhostB js
<script>
var sendEvent = function () {
var xhr = new XMLHttpRequest();
xhr.open("POST", "/home/message?id=4");
xhr.onload = function (e) {
console.log(e);
}
xhr.onerror = function (e) {
console.log(e);
}
xhr.send();
}
</script>
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);
});
here is the upload logic in js
var upload = function(){
if(_file.files.length === 0){
return;
}
var data = new FormData();
data.append('SelectedFile', _file.files[0]);
var request = new XMLHttpRequest();
request.onreadystatechange = function(){
if(request.readyState == 4){
try {
var resp = JSON.parse(request.response);
} catch (e){
var resp = {
status: 'error',
data: 'Unknown error occurred: [' + request.responseText + ']'
};
}
console.log(resp.status + ': ' + resp.data);
}
};
request.upload.addEventListener('progress', function(e){
_progress.style.width = Math.ceil(e.loaded/e.total) * 100 + '%';
}, false);
request.open('POST', 'upload.php');
request.send(data);
}
I run the function every time user selected something, but I only got the first file if user selected multiple files.
That's because you're only adding the first file to your data object:
data.append('SelectedFile', _file.files[0]);
You need to add all your files in the _file.files collection
Something like:
for(var i = 0 ; i < _file.files.length; i++ ) {
data.append('SelectedFile'+i, _file.files[i]);
}
var data = new FormData();
data.append('SelectedFile', _file.files[0]);
Instead of this code, try something like this:
var data = new FormData();
for (var i in _file.files) data.append('SelectedFile'+i, _file.files[i]);