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.
Related
Software versions:
"webtorrent-hybrid": "^4.0.1",
OS X 10.14.4
NPM: 6.13.4
Node: v8.17.0
var WebTorrent = require('webtorrent-hybrid')
var client = new WebTorrent()
client.on('error', (err) => {
console.error(`fatalError ${err.message || err}`);
process.exit(1);
});
client.seed('./c5l.mp4', function (torrent) {
torrent.on('warning', function (err) {
console.warn(err);
});
torrent.on('error', function (err) {
console.error(err);
});
console.log('client.seed done', {
magnetURI: torrent.magnetURI,
ready: torrent.ready,
paused: torrent.paused,
done: torrent.done,
infohash: torrent.infoHash
});
});
Gives me my magnet string. On the frontend I have:
script(src = 'https://cdnjs.cloudflare.com/ajax/libs/webtorrent/0.107.17/webtorrent.min.js')
script.
var client = new WebTorrent()
// working torrentId
var torrentId2 = 'magnet:?xt=urn:btih:c9e15763f722f23e98a29decdfae341b98d53056&dn=Cosmos+Laundromat&tr=udp%3A%2F%2Fexplodie.org%3A6969&tr=udp%3A%2F%2Ftracker.coppersurfer.tk%3A6969&tr=udp%3A%2F%2Ftracker.empire-js.us%3A1337&tr=udp%3A%2F%2Ftracker.leechers-paradise.org%3A6969&tr=udp%3A%2F%2Ftracker.opentrackr.org%3A1337&tr=wss%3A%2F%2Ftracker.btorrent.xyz&tr=wss%3A%2F%2Ftracker.fastcast.nz&tr=wss%3A%2F%2Ftracker.openwebtorrent.com&ws=https%3A%2F%2Fwebtorrent.io%2Ftorrents%2F&xs=https%3A%2F%2Fwebtorrent.io%2Ftorrents%2Fcosmos-laundromat.torrent'
// failing torrentId
var torrentId5 = 'magnet:?xt=urn:btih:f9435fb103d53a0b3cce14afbae867cc6999d76b&dn=c5l.mp4&tr=udp%3A%2F%2Fexplodie.org%3A6969&tr=udp%3A%2F%2Ftracker.coppersurfer.tk%3A6969&tr=udp%3A%2F%2Ftracker.empire-js.us%3A1337&tr=udp%3A%2F%2Ftracker.leechers-paradise.org%3A6969&tr=udp%3A%2F%2Ftracker.opentrackr.org%3A1337&tr=wss%3A%2F%2Ftracker.openwebtorrent.com'
client.add(torrentId5, function (torrent) {
// Torrents can contain many files. Let's use the .mp4 file
var file = torrent.files.find(function (file) {
console.log(file);
return file.name.endsWith('.mp4')
})
// Display the file by adding it to the DOM.
// Supports video, audio, image files, and more!
file.appendTo('body')
})
When I have the working torrentId the video loads as expected. When I sub it out with the magnet url that was created via the webtorrent-hybrid package I first get some errors:
WebSocket connection to 'wss://tracker.fastcast.nz/' failed: Error in connection establishment: net::ERR_NAME_NOT_RESOLVED
Great, so I remove that tracker from the querystring, try again:
WebSocket connection to 'wss://tracker.btorrent.xyz/' failed: Unknown reason
Great, remove it again I get something that just hangs and nothing happens.
If I use the magnet on Brave it just hangs at Loading the torrent file list and the spinner endlessly spins.
What's going on? Thanks
// working torrentId
var torrentId2
magnet:?xt=urn:btih:c9e15763f722f23e98a29decdfae341b98d53056&dn=Cosmos+Laundromat&tr=udp%3A%2F%2Fexplodie.org%3A6969&tr=udp%3A%2F%2Ftracker.coppersurfer.tk%3A6969&tr=udp%3A%2F%2Ftracker.empire-js.us%3A1337&tr=udp%3A%2F%2Ftracker.leechers-paradise.org%3A6969&tr=udp%3A%2F%2Ftracker.opentrackr.org%3A1337&tr=wss%3A%2F%2Ftracker.btorrent.xyz&tr=wss%3A%2F%2Ftracker.fastcast.nz&tr=wss%3A%2F%2Ftracker.openwebtorrent.com&ws=https%3A%2F%2Fwebtorrent.io%2Ftorrents%2F&xs=https%3A%2F%2Fwebtorrent.io%2Ftorrents%2Fcosmos-laundromat.torrent
is/are a well seeded file(s) is means it works 90-100%
// failing torrentId
var torrentId5 = 'magnet:?xt=urn:btih:f9435fb103d53a0b3cce14afbae867cc6999d76b&dn=c5l.mp4&tr=udp%3A%2F%2Fexplodie.org%3A6969&tr=udp%3A%2F%2Ftracker.coppersurfer.tk%3A6969&tr=udp%3A%2F%2Ftracker.empire-js.us%3A1337&tr=udp%3A%2F%2Ftracker.leechers-paradise.org%3A6969&tr=udp%3A%2F%2Ftracker.opentrackr.org%3A1337&tr=wss%3A%2F%2Ftracker.openwebtorrent.com'
is none or low seeded file(s) is means it works 0.1-10%
When I have the working torrentId the video loads as expected. When I
sub it out with the magnet url that was created via the
webtorrent-hybrid package I first get some errors:
WebSocket connection to 'wss://tracker.fastcast.nz/' failed: Error in
connection establishment: net::ERR_NAME_NOT_RESOLVED
Great, so I remove that tracker from the querystring, try again:
WebSocket connection to 'wss://tracker.btorrent.xyz/' failed: Unknown
reason
Great, remove it again I get something that just hangs and nothing
happens.
If I use the magnet on Brave it just hangs at Loading the torrent file
list and the spinner endlessly spins.
What's going on? Thanks
WebSocket connection to 'wss://tracker.fastcast.nz/' failed: Error in
connection establishment: net::ERR_NAME_NOT_RESOLVED
wss://tracker.fastcast.nz/ is dead and discontinued to support by the owner in year 2019
WebSocket connection to 'wss://tracker.btorrent.xyz/' failed: Unknown reason
is a busy tracker, the response rate is too long and runs in a cheap server due to low funding. so it works 30-90%. so the result is failed: Unknown reason
If I use the magnet on Brave it just hangs at Loading the torrent file
list and the spinner endlessly spins.
Webtorrent clients have some issues downloading/playing large files and unsupported file formats like .mkv (video/x-Matroska). And you can not see any notification if there is an error(s). It just hangs up.
So the problem is when I try to initiate a new WebSocket to a remote host, sometimes the browser's console prints a red error message and complains about a refused connection, here is the message:
Error in connection establishment: net::ERR_CONNECTION_REFUSED
Having an error is fine since the remote host might be not responding sometimes, but the fact that I cannot handle this error message is very annoying.
Is there any way to either handle this error message or check whether the remote host accepts the WebSocket connection before initializing one in my JavaScript code??
Several possibilities come to mind:
Add a WebSocket.onerror error handler
myWebSocket.onerror = myEventHandler;
Wrap your "connect" in a try/catch block
try {
const connection = new WebSocket(myUrl);
...
}
catch(error) {
console.error(error);
}
Structure your code such that your I/O is event driven:
https://developer.mozilla.org/en-US/docs/Web/API/WebSocket#Examples
// Create WebSocket connection.
const socket = new WebSocket('ws://localhost:8080');
// Connection opened
socket.addEventListener('open', function (event) {
socket.send('Hello Server!');
});
// Listen for messages
socket.addEventListener('message', function (event) {
console.log('Message from server ', event.data);
});
// Handle errors
socket.addEventListener('error', function (event) {
console.log('WebSocket error observed:', event);
});
ADDENDUM:
The above methods allow you to completely handle a websockets exception.
Regardless of whether the exception is handled or not, the Chrome debugger will tell you if an exception has occurred. This is a Good Thing. It's called a "First-Chance Exception":
https://learn.microsoft.com/en-us/security-risk-detection/concepts/first-chance-exception
.. it is known a “first chance” exception – the debugger is given the
first chance of inspecting the exception prior to the application
handling it (or not).
In Microsoft's Visual Studio debugger, there's a little checkbox you can use to "gag" first chance exceptions. I'm not aware of any similar "checkbox" in Chrome debugger.
POSSIBLE SUGGESTIONS:
Chrome debugger has a "filter". EXAMPLE FILTER REGEX: ^((?!ERR_CONNECTION_REFUSED).)*$
This link suggests you might be able to use the filter to "Hide Network Messages" (I haven't tried it myself). See also this link.
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.
I am trying to setup SignalR at my ASP.NET MVC site and a Javascript client.
This is my client:
#section scripts{
<script src="~/Scripts/jquery.signalR-2.0.2.min.js"></script>
<script type="text/javascript">
$(function () {
var connection = $.connection('/MY_ENDPOINT');
connection.received(function (data) {
$('#chatArea').append('>>' + data + "\r\n");
});
connection.start().done(function () {
$("#send").click(function () {
connection.send($('#msg').val());
$("#msg").val("");
});
});
connection.error(function (e) {
console.log(e);
});
});
</script>
}
Of course, I have the corresponding HTML elements chatArea and msg. In server, here is what I did:
Installed SignalR (latest version currently, 2.0.2) through NuGet.
Added app.MapSignalR("MY_ENDPOINT", new Microsoft.AspNet.SignalR.HubConfiguration()); in startup configuration, made sure it is called before registering auth methods.
I've subclassed PersistentConnection and overridden OnConnected and OnReceived methods.
However, when I run my app and navigate to the page, I can see that my endpoint's negotiate and connect methods are called, they both return OK (HTTP 200). I try to send anything using the webpage by clicking the "send" button, and at the server side I'm getting this error:
A first chance exception of type 'Newtonsoft.Json.JsonReaderException'
occurred in Newtonsoft.Json.dll
Additional information: Unexpected character encountered while
parsing value: a. Path '', line 0, position 0.
What could be the cause of this error?
UPDATE: I also have an iOS app with the SignalR-ObjC framework, and I can connect. However, when I try to send any data over it, I'm getting:
2014-03-06 19:39:39.853 Tanisalim[54987:70b] Websocket error: Error Domain=AFNetworkingErrorDomain Code=-1011 "Request failed: internal server error (500)" UserInfo=0xade84e0 {NSErrorFailingURLKey=http://10.211.55.3/api/socket/send?transport=longPolling&connectionData=(null)&connectionToken=xybYQ8ItTN0IWUbyrosuHy%2F3jN0krIyHLO6b6Gq8VdC3orwRRGkVSIgtYkNQINVLhRMW77cX%2BU2LiHxoe0eDE3ZumT7JrObJcQ%2FXyHiP25%2BQy%2BZizHEHbsPyBBomERoI, NSLocalizedDescription=Request failed: internal server error (500), NSUnderlyingError=0xade1290 "Request failed: unacceptable content-type: text/html"
Still, no server-side breakpoints are hit.
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.