I'm runing a localhost adonisjs project with a websocket. I followed the adonis get started here. Everything in the server looks ok, but when I tried to connect in my react-native application a got this error:
{
"isTrusted": false,
"message": "Expected HTTP 101 response but was '400 Bad Request'",
}
This is my cliente code:
const ws = new WebSocket("ws://192.168.0.11:3333")
ws.onopen = () => {
ws.send(JSON.stringify({
t: 1,
d: { topic: 'prelista:5999c0ea-6bbb-4e0f-9496-f62658bbac5' }
}))
}
ws.onmessage = (e) => {
console.log(e)
}
ws.onerror = (event) => {
console.log(event)
}
This is my server code:
'use strict'
const Ws = use('Ws')
Ws.channel('prelista:*', ({ socket }) => {
console.log(socket.topic)
})
I found my mistake. Whe we use Adonis websocket on the server side, we need to add /adonis-ws in the end of ws path. Well, changed this const ws = new WebSocket("ws://192.168.0.11:3333")
to this const ws = new WebSocket("ws://192.168.0.11:3333/adonis-ws")
worked now ๐
Related
I have a two webservers both running https with the same certificates, I have a main shard that the user connects to example.com, they retrieve some data and try to connect to an ip address on the 2nd shard via websocket.
But no matter what I configure I get an Error 1006 on the client side when connecting to the 2nd shard. Firefox devtooling gives me multiple errors - ssl_error_bad_cert_domain, SSL_ERROR_RX_RECORD_TOO_LONG.
The certificates are issued and signed, I was wondering where I should go from here. Thanks :)
SHARD2
const options = {
key: './server.key',
cert: './server.cert'
};
var https = require('https').Server(options);
https.listen(443, function () {
// console.log('Https listening on *: 443');
});
let WebSocket = require('ws');
let socket = new WebSocket.Server({ server:https });
socket.on('connection', function (ws, req) {
ws.on('message', (msgRaw) =>{
});
ws.on('close', function(code, reason) {
});
ws.on('error', function(error) {
console.log(error);
ws.close();
});
});
CLIENT
function connect() {
"use strict";
window.WebSocket = window.WebSocket || window.MozWebSocket;
if (!window.WebSocket) {
alert('Your browser doesn\'t support WebSocket');
return;
}
wss = new WebSocket('wss://123.123.123.120/:443');
wss.onmessage = function(event) {
};
wss.onerror = function(event) {
console.log(`wss error: ${JSON.stringify(event)}`);
};
wss.onclose = function(event) {
};
}
Useful sys diagram?
I am trying to setup slack bot and facing below issue.
Error: Slack request signing verification failed
I am exactly following this YT tutorial, even tried git clone his repo to try out but still facing same error.
I even tried to search other slack bot setup tutorial and come back to same issue.
Please help if any of you have experience in fixing this.
Followed tutorial: https://www.youtube.com/watch?v=Awuh2I6iFb0
-> Environment: NodeJS
-> app.js file
require('dotenv').config();
const { WebClient } = require('#slack/web-api');
const { createEventAdapter } = require('#slack/events-api');
const slackSigningSecret = process.env.SLACK_SIGNING_SECRET;
const slackToken = process.env.SLACK_TOKEN;
const port = process.env.SLACK_PORT || 3000;
const slackEvents = createEventAdapter(slackSigningSecret);
const slackClient = new WebClient(slackToken);
slackEvents.on('app_mention', (event) => {
console.log(`Got message from user ${event.user}: ${event.text}`);
(async () => {
try {
await slackClient.chat.postMessage({ channel: event.channel, text: `Hello <#${event.user}>! :tada:` })
} catch (error) {
console.log(error.data)
}
})();
});
slackEvents.on('error', console.error);
slackEvents.start(port).then(() => {
console.log(`Server started on port ${port}`)
});
Full error code:
Error: Slack request signing verification failed
at Server. (/Users/byao/CD/playground/slackcicd/node_modules/#slack/events-api/dist/http-handler.js:148:39)
at Server.emit (events.js:375:28)
at parserOnIncoming (_http_server.js:897:12)
at HTTPParser.parserOnHeadersComplete (_http_common.js:126:17) {
code: 'SLACKHTTPHANDLER_REQUEST_SIGNATURE_VERIFICATION_FAILURE'
}
Very appreciated and full of thank you if any of you are willing to help!
I am using nodejs to run the server, there is no log file
This is my server.js
const https = require('https');
const fs = require('fs');
const ws = require('ws');
const options = {
key: fs.readFileSync('key.pem'),
cert: fs.readFileSync('cert.pem')
};
const wss = new ws.Server({noServer: true});
function accept(req, res) {
// all incoming requests must be websockets
if (!req.headers.upgrade || req.headers.upgrade.toLowerCase() != 'websocket') {
res.end();
return;
}
// can be Connection: keep-alive, Upgrade
if (!req.headers.connection.match(/\bupgrade\b/i)) {
res.end();
return;
}
wss.handleUpgrade(req, req.socket, Buffer.alloc(0), onConnect);
}
function onConnect(ws) {
ws.on('message', function (message) {
let name = message.match(/([\p{Alpha}\p{M}\p{Nd}\p{Pc}\p{Join_C}]+)$/gu) || "Guest";
ws.send(`${name}!`);
//setTimeout(() => ws.close(1000, "Bye!"), 5000);
});
}
https.createServer(options, function (req, res) {
res.writeHead(200);
res.end("hello world\n");
}).listen(8000);
This is my code in react
componentDidMount() {
var connection = new WebSocket('wss://localhost:8000/');
connection.onopen = function(e) {
connection.send("add people");
};
connection.onmessage = function(event) {
// alert(`[message] Data received from server: ${event.data}`);
console.log("output ", event.data);
};
}
While I am trying to connect with web-socket with my jsx file its give me an error which is Firefox canโt establish a connection to the server at wss://localhost:8000/.
Your implementaion needs some changes. In the backend server, you forgot to call the onConnect function. So your ws.on method will never call.
Also, you imported the ws and create a WebSocket server wss, but you add some event listener on ws wrongly, you should add listener on your Websocket instance (wss):
// rest of the codes ...
const was = new ws.Server({noServer: true})
wss.on('connection`) {
// do something here ...
}
// rest of the codes ...
https.createServer(options, () => {
// do something here ...
})
There are some examples of how to create the WebSocket server along with the HTTP server on ws npm page.
I just want to get live data from Mysql DB on the UI Reactjs. So that the user need not to refresh it always. After looking over some posts end up creating a socket.io connection so that the client can speak to the server. This is what I tried to get into:
server.js
const express = require("express");
const http = require("http");
const socketIo = require("socket.io");
var assert = require('assert');
const port = process.env.PORT || 4001;
const index = require("./routes/index");
const app = express();
app.use(index);
const server = http.createServer(app);
const io = socketIo(server);
const mysql = require('mysql');
var startDate ;
var endDate ;
var loopVariable = 1;
io.on("connection", (socket) => {
console.log("New client connected");
const con = mysql.createConnection({
host: 'localhost',
user: 'root',
password: 'root',
database: 'localstatus',
debug: false,
});
console.log('Connection established ',(loopVariable++));
socket.on("FromUI", (data) => {
startDate = data.startDate;
endDate = data.endDate;
});
var initial_result;
setInterval(() => {
con.query('SELECT * FROM table where start_time BETWEEN ? and ?', [ startDate, endDate ],(err,rows) =>
{
if(err) {
console.log ('error', err.message, err.stack)
}else {
}
if(JSON.stringify(rows) === JSON.stringify(initial_result)){
}else{
if(Changed(initial_result, rows)) {
var result = [];
for (var row in rows) {
var results = [];
results.push({
Id: rows[row].id,
status: rows[row].t_status,
});
result.push({ returnValue:"true",
object: {Id: rows[row].id,
status: rows[row].t_status,
}});
}
socket.emit('FromAPI', result);
}
initial_result = rows;
}
})
function Changed(pre, now) {
if (pre != now)
{
return true
}else{
return false
}}
}, 1000);
socket.on('disconnect', function() {
socket.disconnect();
loopVariable--;
});
});
server.listen(port, () => console.log(`Listening on port ${port}`));
client.js
import React, { useState, useEffect, Component } from "react";
import socketIOClient from "socket.io-client";
import TableUsingReactTable from "./TableUsingReactTable.js";
const ENDPOINT = "http://localhost:4001";
export default function App(){
const [response, setResponse] = useState([]);
useEffect(() => {
const socket = socketIOClient(ENDPOINT);
try{
socket.on("FromAPI", data => {
setResponse(data);
});
}catch (error) {
console.log(error);
}
return () => {
socket.on("disconnect")
socket.disconnect();
};
}, []);
console.log(response)
return (<TableUsingReactTable response={response}></TableUsingReactTable>)
}
I think the socket gets disconnected when the tab gets closed, but what happens when is tab is not in use? And how to disable it when not in use? Even when all the tabs are closed then also the RAM increases. How to reduce the RAM when sockets get closed? And how does socket.io behave when at the same time many hit the URL? Moreover, sometimes I did face the issue as:
code: 'ER_CON_COUNT_ERROR',
errno: 1040,
sqlMessage: 'Too many connections',
sqlState: undefined,
fatal: true
How to handle this case too? I m new to this and not understanding how to proceed further. Can someone help me with this? Thanks a lot.
Firstly, you don't actually need Socket.IO for this use case. Server-Sent Events/EventSource API are fine for this, as you're only sending data in one direction. This gives you the benefit of not needing to load Socket.IO libraries.
Now, the real problem is that you're creating a separate MySQL connection for each individual client. Rather than calling mysql.createConnection() every time a new client connects, you can connect to your database once. (There are situations where this isn't appropriate, but since you're just doing some basic SELECT queries, this is fine.)
I am trying to get a subscription up and running with ApolloServer (v 2.2.2). I had a setup that all-of-a-sudden just stopped working. When I try to connect to the subscription in graphiql/PlaygroundI get the error:
{
"error": "Could not connect to websocket endpoint ws://localhost:4000/graphql. Please check if the endpoint url is correct."
}
As I have rest-endpoints in my app I need to have express but I can't get the minimal example from below running:
import http from 'http';
import { ApolloServer, PubSub } from 'apollo-server-express';
import express from 'express';
const pubsub = new PubSub();
// The DB
const messages = [];
const typeDefs = `
type Query {
messages: [String!]!
}
type Mutation {
addMessage(message: String!): [String!]!
}
type Subscription {
newMessage: String!
}
schema {
query: Query
mutation: Mutation
subscription: Subscription
}
`;
const resolvers = {
Query: {
messages() {
return messages;
}
},
Mutation: {
addMessage(root, { message }) {
let entry = JSON.stringify({ id: messages.length, message: message });
messages.push(entry);
pubsub.publish('newMessage', { entry: entry });
return messages;
},
},
Subscription: {
newMessage: {
resolve: (message) => {
return message.entry;
},
subscribe: () => pubsub.asyncIterator('newMessage'),
},
},
};
const app = express();
const PORT = 4000;
const server = new ApolloServer({
typeDefs,
resolvers,
subscriptions: {
onConnect: () => console.log('Connected to websocket'),
}
});
server.applyMiddleware({ app })
const httpServer = http.createServer(app);
server.installSubscriptionHandlers(httpServer);
httpServer.listen(PORT, () => {
console.log(`๐ Server ready at http://localhost:${PORT}${server.graphqlPath}`)
console.log(`๐ Subscriptions ready at ws://localhost:${PORT}${server.subscriptionsPath}`)
})
The other endpoints work fine but it is unable to create the WebSocket. As far as I understand it I shouldn't have to use a different server or port (see https://www.ably.io/concepts/websockets). I've tinkered with SubsciptionServer but this should be handled by installSubscriptionHandlers (here's the code).
The it turns out that Firefox has issues with websockets (see this bug report that has been re-appeared even after the supposed fix).
In Firefox it works directly after starting a novel browser but after some hot reloading it stops working. The following helps out with starting out fresh but not with the reloading issue:
const wsLink = new WebSocketLink({
uri: SUBSCRIPTION_URI,
options: {
reconnect: true,
timeout: 20000,
lazy: true,
},
});
window.addEventListener('beforeunload', () => {
// #ts-ignore - the function is private in typescript
wsLink.subscriptionClient.close();
});
I think the bug is related to this SO-question: "websocket was interrupted while page is loading" on Firefox for Socket.io
If you want to test different solutions I've created an example repo: https://github.com/gforge/subscription_example that works both by itself and with a Docker container.
A lot of time has passed and now I faced with the same problem and I found a solution.
import { createServer } from 'http';
const app = express();
const server = new ApolloServer({});
server.applyMiddleware({ app });
const httpServer = createServer(app);
server.installSubscriptionHandlers(httpServer);
server.listen()
Works for me