websocket-rails, websocket handshake error - javascript

I followed the docs on the websocket-rails github wiki page, but couldn't overcome this difficulty, I get this error with chrome:
WebSocket connection to 'ws://0.0.0.0:3000/websocket' failed: Error during WebSocket handshake: Unexpected response code: 301
I installed the websocket-rails gem, generated the install, I set successfully config.middleware.delete Rack::Lock in development.rb; I'm using Rails 4.
I got in the view:
<script type="text/javascript">
var dispatcher = new WebSocketRails('0.0.0.0:3000/websocket');
</script>
I got in my chat_controller.rb:
class ChatController < WebsocketRails::BaseController
def initialize_session
puts "Session Initialized"
end
def user_connected
puts 'user connected'
end
end
in my events.rb:
WebsocketRails::EventMap.describe do
subscribe :client_connected, :to => ChatController, :with_method => :user_connected
end
As you can see, my goal is to display "Session Initialized", and "user connected", in my thin server console each time that someone goes on a page. Between, I run the server with bundle exec thin start, but I got a javascript error instead (websocket connection failed error 301).

Thanks to the members of the Websocket Rails IRC, I found out that in my route, I was appending the locale before every path, so it coudln't find it.
Check your routes.rb if someone hit that issue too !

Related

SignalR - Connection stopped when multiple tabs are opened - Message is incomplete

On the frontend of my application I use the #microsoft/signalr library to send off requests to my backend hubs. This works okay in a single tab, but when a second tab is open an error is outputted to the console of the first tab and the connection stops. It's almost as if the second tab is taking over for some reason, when really I believe both should be connected to the hub on different connections with different connection ids. The error I receive in the console is as follows:
[2021-04-23T09:34:22.762Z] Information: WebSocket connected to wss://localhost:6001/ptwHub?id=39HKWle3NU0eTjFxcNWsiQ.
Utils.js:218 [2021-04-23T09:34:32.895Z] Error: Connection disconnected with error 'Error: Message is incomplete.'.
./node_modules/#microsoft/signalr/dist/esm/Utils.js.ConsoleLogger.log # Utils.js:218
./node_modules/#microsoft/signalr/dist/esm/HttpConnection.js.HttpConnection.stopConnection # HttpConnection.js:542
transport.onclose # HttpConnection.js:479
./node_modules/#microsoft/signalr/dist/esm/WebSocketTransport.js.WebSocketTransport.close # WebSocketTransport.js:189
webSocket.onmessage # WebSocketTransport.js:129
ptw.ts:22 Error: Message is incomplete.
at Function../node_modules/#microsoft/signalr/dist/esm/TextMessageFormat.js.TextMessageFormat.parse (TextMessageFormat.js:13)
at JsonHubProtocol../node_modules/#microsoft/signalr/dist/esm/JsonHubProtocol.js.JsonHubProtocol.parseMessages (JsonHubProtocol.js:36)
at HubConnection../node_modules/#microsoft/signalr/dist/esm/HubConnection.js.HubConnection.processIncomingData (HubConnection.js:507)
at WebSocketTransport.HubConnection.connection.onreceive (HubConnection.js:73)
at WebSocket.webSocket.onmessage (WebSocketTransport.js:126)
The code to connect to the hub is as follows:
let connection = new signalR.HubConnectionBuilder().withUrl("https://localhost:6001/hub").build();
connection.on('knowledgeBaseUpdated', (userId: number) => {
alert(`User ${userId} has updated the knowledge base. Please refresh.`);
});
connection.start().catch(err => console.log(err));
Really not sure why the second tab would just take over the connection instead of creating a new connection. There is obviously an issue here somewhere but I'm really not sure where so any help would be really appreciated.
EDIT
I've enabled client side debugging for signalr and get the following output. The line which starts with HttpConnection.stopConnection is the line which appears when a new connections is attempted from a different tab.
[2021-04-26T09:50:00.084Z] Debug: Starting HubConnection.
Utils.js:228 [2021-04-26T09:50:00.096Z] Debug: Starting connection with transfer format 'Text'.
Utils.js:228 [2021-04-26T09:50:00.099Z] Debug: Sending negotiation request: https://localhost:6001/ptwHub/negotiate?negotiateVersion=1.
Utils.js:228 [2021-04-26T09:50:00.365Z] Debug: Selecting transport 'WebSockets'.
Utils.js:224 [2021-04-26T09:50:00.667Z] Information: WebSocket connected to wss://localhost:6001/ptwHub?id=14d1O9-cj544_-SHeZ2fgw.
Utils.js:228 [2021-04-26T09:50:00.667Z] Debug: The HttpConnection connected successfully.
Utils.js:228 [2021-04-26T09:50:00.668Z] Debug: Sending handshake request.
Utils.js:224 [2021-04-26T09:50:00.669Z] Information: Using HubProtocol 'json'.
Utils.js:228 [2021-04-26T09:50:13.079Z] Debug: Server handshake complete.
Utils.js:228 [2021-04-26T09:50:13.081Z] Debug: HttpConnection.stopConnection(Error: Message is incomplete.) called while in state Connected.
Utils.js:218 [2021-04-26T09:50:13.081Z] Error: Connection disconnected with error 'Error: Message is incomplete.'.
./node_modules/#microsoft/signalr/dist/esm/Utils.js.ConsoleLogger.log # Utils.js:218
./node_modules/#microsoft/signalr/dist/esm/HttpConnection.js.HttpConnection.stopConnection # HttpConnection.js:542
transport.onclose # HttpConnection.js:479
./node_modules/#microsoft/signalr/dist/esm/WebSocketTransport.js.WebSocketTransport.close # WebSocketTransport.js:189
webSocket.onmessage # WebSocketTransport.js:129
Utils.js:228 [2021-04-26T09:50:13.082Z] Debug: HubConnection.connectionClosed(Error: Message is incomplete.) called while in state Connecting.
Utils.js:228 [2021-04-26T09:50:13.083Z] Debug: Hub handshake failed with error 'Error: Message is incomplete.' during start(). Stopping HubConnection.
Utils.js:228 [2021-04-26T09:50:13.083Z] Debug: Call to HttpConnection.stop(Error: Message is incomplete.) ignored because the connection is already in the disconnected state.
Utils.js:228 [2021-04-26T09:50:13.084Z] Debug: HubConnection failed to start successfully because of error 'Error: Message is incomplete.'.
When the connection starts on a particular tab, I can see the connection has started and I get a single message when I look at the Network tab of Chrome Dev Tools. When I open the second tab, another message is sent to the first time which looks like an error message.. it weirdly contains a load of red dot characters? I
mage attached below. Please ignore the fact it's called ptwHub as I removed the ptw part previously to make it easier for the readers to understand.

Websocket-Rails Channel 'Error during WebSocket Handshake'

I'm trying to use websocket-rails to broadcast live routes as they come in to my site. However, I'm unable to get any messages to be published. I've read all of the help I could find, and I can't seem to get a solution.
Here is what the javascript I have in application.html.erb:
var route_name = window.location.pathname + window.location.search;
$.post("/realtimeroutes",
{ data: { route_name: route_name} },
function(response) {
}
);
This data is handed off to a rails controller method realtime_routes which looks like this:
def realtime_routes
puts '*** The Route Data is: ' + params[:data][:route_name]);
new_route = RouteCatcher.new(route_name: params[:data][:route_name]
if new_route.save
route = {route_name: params[:data][:route_name]}
puts '*** Right before the Message is sent ***'
WebsocketRails[:new_route].trigger('new', route)
puts '*** Right After the Message is sent ***'
render nothing: true
else
render nothing: true
end
end
To this point everything is fine. updates are happening in the DB and both the before and after messages are printing to the console, but there is no Websocket Message fired.
Next I have this javascript listening in realtime.html.erb:
var dispatcher = new WebSocketRails(window.location.host + '/websocket');
var channel = dispatcher.subscribe('new_route');
channel.bind('new', function(route) {
console.log('********** Inside Bind Event');
console.log('********** a new route '+ route.route_name +' arrived!');
});
Nothing is ever being received on the bind event and when I look in the Console on Chrome, I get:
'Uncaught ReferenceError: WebSocketRails is not defined'
So I'm absolutely stuck here as I've followed every bit of documentation I can find and really have no idea where to go. Any help with this is greatly appreciated.
UPDATE: That was an initialization error because the WebSocketRails was being rendered before the rest of the application js.
However, now I am getting the error:
WebSocket connection to 'ws://localhost:3000/websocket' failed: Error during WebSocket handshake: Unexpected response code: 301
After reading further about other people with the same error, it seems prudent to mention that I am using Puma on AWS elasticbeanstalk with SSL in production.

NodeJS Sockets Sometimes Working

So, I have a node server, running expressjs io (uses socket.io), and I'm building a grid map that tracks coordinates in a database.
Only, I've run into a peculiar issue in that my sockets only listen sometimes.
At first there was no error message, and only by chance I let the page run and I got this error.
Uncaught TypeError: Cannot call method '0' of undefined UkPS99A_w96Ae0K570Nt?t=1395276358213&i=0:1
When I click on the file UkPS99A_w96Ae0K570Nt?t=1395276358213&i=0:1 I get this code:
io.j[0]("8::");
If I refresh the page, every few times it will suddenly work find for about 10 tile clicks, and then it stops working. My database is updating properly until the sockets basically die out.
Here is where I send the coordinates in my map:
io.emit("move", {x:this.x,y:this.y});
Server listening:
app.io.route('move', function(req) {
con.getConnection(function(err){
if (err) console.log("Get Connection Error.. "+err);
//removed query because redundant
req.io.emit("talk", {x:req.data.x,y:req.data.y});
});
});
and my socket script:
io.on("talk",function(data) {
console.log(data.x,data.y);
});
My script includes are at the bottom of the page in this order:
<script src="socket.io/socket.io.js"></script>
<script>io = io.connect();</script> <!-- open the socket so the other scripts can use it -->
<script src="../js/sock.js"></script>
<script src="../js/map.js"></script>
Is there something I'm doing wrong to that the socket seems to lose connection and throw some sort of error?
Update: I left the server running longer and a couple more error messages popped up in my console:
Uncaught TypeError: Cannot call method 'close' of null socket.io.js:1967
Uncaught TypeError: Cannot call method 'close' of null socket.io.js:1967
Uncaught TypeError: Cannot call method 'onClose' of null
More update: altered the connection line and added the proper CORS to my server.js
io = io.connect('http://sourceundead.com', {resource : 'socket.io'});
Still the same issue.
You seem to have a connection attrition as you never release them to the pool.
Assuming con is the (bad) name of your pool, instead of
app.io.route('move', function(req) {
con.getConnection(function(err){
if (err) console.log("Get Connection Error.. "+err);
//removed query because redundant
req.io.emit("talk", {x:req.data.x,y:req.data.y});
});
});
you should have something like
app.io.route('move', function(req) {
con.getConnection(function(err, connection){
if (err) console.log("Get Connection Error.. "+err);
//removed query because redundant
req.io.emit("talk", {x:req.data.x,y:req.data.y});
connection.release();
});
});
Be careful that using connections must be done with care to ensure they're always released, and it's a little tedious to do especially when handling errors as soon as you have a few queries to do when doing a task.
At some point you might want to use promises to make that easier. Here's a blog post about using bound promises to ease database querying in node.js.

Node js + Sails js + websocket app crashing every few hours

I am having a problem similar to socket.io issue using sails.js. Every once in a while (once per day, or even few hours, it varies), a visitor to the web site/app will crash Node, seemingly due to the way his websocket client tries to connect. Anyway, here's the crash log:
debug: Lowering sails...
/Volumes/Two/Sites/lsdfinder/node_modules/sails/node_modules/express/node_modules/connect/lib/utils.js:216
return 0 == str.indexOf('s:')
^
TypeError: Cannot call method 'indexOf' of undefined
at exports.parseSignedCookie (/Volumes/Two/Sites/lsdfinder/node_modules/sails/node_modules/express/node_modules/connect/lib/utils.js:216:19)
at Manager.socketAttemptingToConnect (/Volumes/Two/Sites/lsdfinder/node_modules/sails/lib/hooks/sockets/authorization.js:35:26)
at Manager.authorize (/Volumes/Two/Sites/lsdfinder/node_modules/sails/node_modules/socket.io/lib/manager.js:910:31)
at Manager.handleHandshake (/Volumes/Two/Sites/lsdfinder/node_modules/sails/node_modules/socket.io/lib/manager.js:786:8)
at Manager.handleRequest (/Volumes/Two/Sites/lsdfinder/node_modules/sails/node_modules/socket.io/lib/manager.js:593:12)
at Server.<anonymous> (/Volumes/Two/Sites/lsdfinder/node_modules/sails/node_modules/socket.io/lib/manager.js:119:10)
at Server.EventEmitter.emit (events.js:98:17)
at HTTPParser.parser.onIncoming (http.js:2076:12)
at HTTPParser.parserOnHeadersComplete [as onHeadersComplete] (http.js:120:23)
at Socket.socket.ondata (http.js:1966:22)
9 Oct 10:42:24 - [nodemon] app crashed - waiting for file changes before starting...
In config/sockets.js, authorization is set to true. Not sure what else to do, where to fix this. Any suggestions? I can read the Sails docs too, but this appears to be a problem in Express/Connect, no? Thanks.
...René
The problem is that once every so often, a client will connect that has no cookies. Sails.js is using util.parseSignedCookie() from Connect without checking for errors, and therefore an error is thrown. This is what it looks like in Sails:
if (handshake.headers.cookie) {
handshake.cookie = cookie.parse(handshake.headers.cookie);
handshake.sessionID = parseSignedCookie(handshake.cookie[sails.config.session.key], sails.config.session.secret);
}
If you take a look into the cookieParser() middleware of Connect, you can see error checking is required:
if (cookies) {
try {
req.cookies = cookie.parse(cookies);
if (secret) {
req.signedCookies = utils.parseSignedCookies(req.cookies, secret);
req.signedCookies = utils.parseJSONCookies(req.signedCookies);
}
req.cookies = utils.parseJSONCookies(req.cookies);
} catch (err) {
err.status = 400;
return next(err);
}
}
I've created a Gist here that fixes the problem, and will submit a pull request to Sails.js when I have the time. The Gist uses Connect's cookieParser() middleware to automatically handle errors. If you want to use this, modify this file in your modules folder:
node_modules/sails/lib/hooks/sockets/authorization.js
If you are doing a crossdomain request, you could turn off authorization.
In *site_dir/config/sockets.js* set authorization to false. One way of doing it. You can also call your api with something like this
bash
**http://localhost:1337?cookie=smokeybear**
Its is in the comments on the sockets.js file.

enabling LOAD DATA LOCAL INFILE in mysql-libmysqlclient for node?

I need to use LOAD DATA LOCAL INFILE using mysql-libmysqlclient in node. However I get an error
[Error: Query error #1148: The used command is not allowed with this MySQL version]
This does not happen running the same command from sequel pro so the issue is most likely with the connection used by mysql-libmysqlclient.
Anoyone know what parameters to send to mysql-libmysqlclient in order to fix this?
initializing connection:
secrets = stuff
mysql_db = mysql.createConnectionQueuedSync()
mysql_db.initSync()
mysql_db.realConnectSync secrets.host, secrets.user, secrets.password, secrets.database
mysql_db.connectError
module.exports = exports = mysql_db
Sending query:
mysql_db = require('./config/mysql_db')
sql_insert_into = "LOAD DATA local INFILE 'file_to_send.txt'
into table #{table.name}
FIELDS TERMINATED BY ';'
LINES TERMINATED by '\\n'
"
mysql_db.query sql_insert_into, (err, answer)->
console.log "sent " + sql_insert_into
The error I get:
[Error: Query error #1148: The used command is not allowed with this MySQL version]
Minor note: I program in coffee script but this shouldn't change anything
If LOAD DATA LOCAL is disabled, either in the server or the client, a client that attempts to issue such a statement receives the following error message:
ERROR 1148: The used command is not allowed with this MySQL version
You can refer MySql website link below for how to enable:
https://dev.mysql.com/doc/refman/5.5/en/load-data-local.html

Categories

Resources