api – Como posso fazer uma conexao constante entre aplicacoes com php (websockets?)

Eu ainda estou estudando sobre o assunto, não tenho certeza de nada e estou aberto a quaisquer orientacões.

O problema:
recentemente fiz uma API Rest em php para conectar uma aplicacao em .lua com o banco de dados, funciona perfeitamente, porem percebi que apenas gerar uma requisicao por vez não seria eficiente, então comecei a procurar sobre real time e acabei caindo nos Websockets.

Basicamente preciso que a minha aplicacão em .lua troque informacões o tempo todo com a API (ou servidor), vi alguns videos e bibliotecas no Composer, mas no final todos eles acabam com um chat em tempo real, e não é isso que quero.

A minha duvida é: Devo usar as mesmas funcões de um real time chat para esse objetivo ou o que procuro tem outro nome?

fiz uma analise para ver se ficaria viavel usar esse mesmo esquema de chat, mas percebi que teria que “privar” todas as respostas com o servidor e os usuarios, tendo em vista que mais de um usuario se conectaria ao servidor e logicamente nao poderia obter as informacoes de terceiros como em um chat.

Se tiver alguma duvida por favor pergunte.

php – Chat con websockets en Javascript vanilla

¡Hola! Esta vez no quiero pedir ningun “codigo de ejemplo”, estoy creando un chat privado y parece ser que deberia hacerlo con websockets para no sobrecargar el servidor, el problema es que no encuentro como utilizar y crear websockets y crear un chat en vivo con ellos sin utilizar jquery (Odio las librerias externas), lo unico que encontre fue este video, funciono bien, pero no se como pasarlo a un chat en vivo (el lo hace con un grafico pastel), y a pesar de buscar no encuentro ningun lugar para estudiar los websockets sin Jquery, asi que mi pregunta es:

¿Me pueden proporcionar alguna direccion o lo que sea que me ayude para crear un chat en vivo con WebSockets en Vanilla Javascript?

c# – Multiple API calls potentially spawning multiple Websockets – Threading vs Async

I am designing a program with the flow as outlined below. Note, these are all network calls, there is no system I/O (hard drive).

Initially, multiple independent API calls need to happen – they don’t rely on the others at all. The response from these will be processed and if they meet certain criteria, they should spawn a websocket connection and stop their API calling until the socket is closed. For example, if there are 4 API calls happening and one meets the requirements, it stops and connects to a websocket. Now there should be 3 API calls happening as well as a websocket receiving data. There should never be more websockets than the number of initial API calls.

Now, the websocket(s) are also processing the recieved data looking for specific requirements. If any one of the sockets meets the requirement, a SECOND websocket is then connected to. At this point, all outstanding API calls/websockets should close/stop their processing. Only this new websocket should be running looking for its final set of requirements. Once this final set is met, the whole process should restart (meaning the API calls start up again).

Let me walk you through a scenario: 4 API calls start. After 3 seconds one meets the requirements. There are now 3 API calls STILL happening, and 1 websocket running. After 2 seconds, the websocket fails its requirements. There are now 4 API calls happening again. Soon, 2 API calls both meet requirements. Now there are 2 API calls and 2 websockets listening. After another 3 seconds, one of the websockets meets its requirements. All websockets and API calls should stop, and a final websocket is opened. After this final one either succeeds or fails, the initial 4 API calls should be restarted and the process repeats all over again.

My question: Would this benefit from some form of threading (instead of only using async) and if so, what method would you use? Each API call on it’s own thread that spawns its following websockets on it too? Maybe all the API calls on single thread but then spawn off websockets on their own thread? Maybe the whole program can be run in a single thread with good performance? The operations are time sensitive so the faster I can determine requirements being met the better! Thanks in advance!

php – I can’t start connection with WebSockets in EC2

I really need help with websockets, recently I used SSL(Let’s Encrypt) in my website that is in ec2, and I used route 53 for routing, and the website works perfectly with SSL and my DNS, but I can’t start connection with WebSockets and HTTPS, it only works with HTTP, using the port 8080, when I try to start connection with HTTPS under port 8443, Google console says:

WebSocket connection to “mysite” failed: WebSocket opening handshake
timed out

I really don’t know what to do anymore, in my point of view everything is okay with the part of coding but it really looks like a problem involving Apache and SSL, please help me, I’m with this problem there are 2 weeks and I don’t know what to do

AWS:

Ports   Protocol    Source  SecurityGroup
80  tcp 0.0.0.0/0, ::/0 ✔
8080    tcp 0.0.0.0/0, ::/0 ✔
4433    tcp 0.0.0.0/0, ::/0 ✔
22  tcp 0.0.0.0/0   ✔
8443    tcp 0.0.0.0/0, ::/0 ✔
3000    tcp 0.0.0.0/0   ✔
443 tcp 0.0.0.0/0, ::/0 ✔

PHP:

<?php
use RatchetServerIoServer;
use RatchetHttpHttpServer;
use RatchetWebSocketWsServer;
use AnneSocketChat;

    require dirname(__DIR__) . '/vendor/autoload.php';

    $server = IoServer::factory(
        new HttpServer(
            new WsServer(
                new Chat()
            )
         ),
        8433
    );

    $server->run();

JS:

var conn = new WebSocket('wss://example.com:8433/chat.php'); //Using port 8433, it doesn't works as any port, I already tried a lot of ports

Apache

Listen 80

    <VirtualHost *:80>
        DocumentRoot "/var/www/html"
        ServerName "example.com"
        ServerAlias "www.example.com"
    RewriteEngine on
    RewriteCond %{SERVER_NAME} =www.example.com (OR)
    RewriteCond %{SERVER_NAME} =example.com
    RewriteRule ^ https://%{SERVER_NAME}%{REQUEST_URI} (END,NE,R=permanent)
    
    ProxyPreserveHost On
    
    ProxyPass /chat.php/ ws://example.com:8433/
    ProxyPassReverse /chat.php/ ws://example.com:8433/
    </VirtualHost>

websockets – SignalR Handle Multiple Clients in my Scenario

I currently have multiple clients who need to be informed when a customer creates a new order. Each customer is registered to an individual client and customers create orders on my website (each order has a particular client id when created).

I’m currently using polling and each client hits my API every few seconds and gets a list of new items. This is not ideal to say the least! I would like to find a way of finding a more efficient way.

Ideally each client should be pushed/sent each new order as they come in instead of the client continually hitting my server every few seconds. Is this possible with signalR or some other technology?

If it is would signalR be able to wait for a new order then push that order straight out to the client then store the order in the database? Or would signalR be watching the database table and then retrieve a list of new orders? Would this put a load on the DB?

Any ideas would be appreciated.

electrum – How to connect to an ElectrumX server using JavaScript WebSockets?

I’m trying to connect to an ElectrumX server from an HTML webpage. But I can’t get a working connection.

I’ve tried with many servers from Electrum’s servers.json list but none worked.

Here’s the JavaScript code that I tried:

const socket = new WebSocket("ws://electrum.blockstream.info:50002");

// Connection opened
socket.addEventListener("open", () => {
  console.log("Connection opened");
});

socket.addEventListener("close", () => {
  console.log("Connection closed");
});

socket.addEventListener("error", e => {
  console.log("error", e);
});

socket.addEventListener("message", function(event) {
  console.log("Message from server ", event.data);
});

I tried both encrypted (wss) and non-encrypted (ws) connection. I tried several servers and different ports. I couldn’t get it to connect.

Could someone share a working example of JavaScript code connecting to ElectrumX using WebSockets?

same origin policy – Why WebSockets doesn’t apply SOP?

Same-origin policy considers all of these origins to be different:

http://example.com
https://example.com
ws://example.com
wss://example.com

So if a page at https://example.com tried to connect to a WebSocket at wss://example.com SOP would block it if the browser applied the same rules. WebSockets also don’t really use HTTP headers either so there wouldn’t be a way to relax those rules with CORS headers.

Websockets not working

I found nifty little webapp based on the TV show Jeopardy. It uses websockets which I can’t seem to get running.

The code for the game can be found here: https://github.com/tpavlek/Jeopardy

I’m pretty sure I have all the mods I need enabled, here’s a list of installed ones.

access_compat.load
alias.conf
alias.load
auth_basic.load
authn_core.load
authn_file.load
authz_core.load
authz_host.load
authz_user.load
autoindex.conf
autoindex.load
deflate.conf
deflate.load
dir.conf
dir.load
env.load
filter.load
http2.load
mime.conf
mime.load
mpm_prefork.conf
mpm_prefork.load
negotiation.conf
negotiation.load
php7.2.conf
php7.2.load
proxy.conf
proxy_connect.load
proxy_http2.load
proxy_http.load
proxy.load
proxy_wstunnel.load
reqtimeout.conf
reqtimeout.load
rewrite.load
setenvif.conf
setenvif.load
status.conf
status.load

My apache conf file is this:

<VirtualHost *:80>
  DocumentRoot /home/user/Jeopardy/client/
  ServerName jeopardy.url.tld

  <Directory /home/user/Jeopardy/client/>
     Options +FollowSymlinks
     AllowOverride All
     Require all granted
  </Directory>
    <FilesMatch .php$>
        SetHandler application/x-httpd-php
    </FilesMatch>

  RewriteEngine on
    RewriteCond %{HTTP:Upgrade} =websocket
    RewriteRule /(.*) ws://localhost:9001/$1 (P,L)

  ProxyPass /ws ws://localhost:9001/
  ProxyPreserveHost On
  ProxyVia full

  <Proxy>
    Order deny,allow
    Allow from all
  </Proxy>

  ErrorLog ${APACHE_LOG_DIR}/jeopardy-error.log
  CustomLog ${APACHE_LOG_DIR}/jeopardy-access.log combined

</VirtualHost>

Code (markup):

When I connect to the site on port 80 the site loads up, I can select Player 1, 2, or 3 and the game board loads. It’s just at this point where WebSockets are needed that it fails.

I’d love to get this going to offer an activity for my Scout Troop while we are stuck holding virtual meetings only.

Thanks,
SEMrush

 

websockets – Preferred framework for caching user query subscription?

Our users log in request for Live data. That request comes in the form of a query like

{
“type”:”weather”,
“location”:”London”
}

User will not only receive the current weather of London but also now he is subscribed to live weather data of London.

Our application receives wether data for various cities. Whenever application receives some data, that goes through active subscriptions if it belongs to any of the active subscriptions then an updated response will be sent to the user.

Apache Storm is used to process wether messages and Cassandra is used to persist weather data. Which framework is best suited To keep active cached active user subscriptions so that Storm can connect to that while processing the data?

react.js – Update the status with React and Websockets

I am working on a reaction app with Websocket. In this app there is a socket event listener that returns three types: add. change, and remove, Certain status updates are performed based on the type of reception.

My question would be based on the code below, I have to mutate it correctly users State because I'm not sure if it will follow the principle of the reaction in terms of updating states.

ws.on("connect", () => {
  console.log("connected");

  ws.emit("load");
});

ws.on("feed", response => {
  const prev = response.old_val;
  const next = response.new_val;
  const type = response.type;
  setUsers(users => {
    let currentUser = (...users);
    let index;
    switch (type) {
      case "add":
        return (...users, next);
      case "change":
        index = users.findIndex(u => u.id === next.id);
        currentUser(index).name = next.name;
        return currentUser;
      case "remove":
        index = users.findIndex(u => u.id === prev.id);
        currentUser.splice(index, 1);
        return currentUser;
      default:
        return currentUser;
    }
  });
});