SignalR not hitting OnConnected and giving Newtonsoft.Json.JsonReaderException - javascript

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.

Related

Sending 500 ("Server Error") response when visiting any url in Sails App

I am using Sails and Mysql to handle the database of my app. I recently clicked on a chrome autofill URL that took me to a 404'd page, since that url localhost:1337/companies was not active in this project.
Ever since I did that, my app returns
error: Sending 500 ("Server Error") response:
Error (E_UNKNOWN) :: Encountered an unexpected error
: ER_BAD_FIELD_ERROR: Unknown column 'NaN' in 'where clause'
and
Details: Error: ER_BAD_FIELD_ERROR: Unknown column 'NaN' in 'where clause'
any time I go to a url in my app. I tried cloning my app and relinking the database to no avail. I see this is a common issue people run into with sails, but none of the mentioned solutions were able to fix it for me.
Everything was working before I clicked that URL which makes me believe it may be a route issue, but the app still works, it will just fill up my terminal with the above errors.
Any help is greatly appreciated!
Edit: this is the custom API call I was working on in my controller.js when I started seeing the error:
winner: function (req, res) {
User.findOne({id: req.param('id')}).exec(function(err, user) {
if (err) {
return res.negotiate(err);
}
else {
var u = user;
u.totalwins++;
u.save();
sails.io.sockets.emit("chat", {verb:"score", data:{id: req.param('id'), name: user.name}});
}
});
}
Also receiving this error in my chrome-browser console:
:1337/user/quizzes Failed to load resource: the server responded with a status of 500 (Internal Server Error)

Sample JavaScript can't connect to Ruby WebSocket server

I would like to fiddle with websockets a bit. I installed a Ruby gem called "websocket-ruby" (https://github.com/imanel/websocket-ruby) I started a pry / IRB session and typed:
require "websocket"
#handshake = WebSocket::Handshake::Server.new(:host => "localhost", :port => 8080,:secure=>true)
This starts a websocket server as far as I know. Then I opened in my browser the Javascript HTML page which attempt to connect to the server:
<!doctype html>
<html lang="en">
<head>
<title>Websocket Client</title>
</head>
<body>
<script>
var exampleSocket = new WebSocket("wss://localhost:8080");
exampleSocket.onopen = function (event) {
exampleSocket.send("Can you hear me?");
};
exampleSocket.onmessage = function (event) {
console.log(event.data);
}
</script>
</body>
</html>
But it says in the console log:
failed: Error in connection establishment: net::ERR_CONNECTION_REFUSED
I tried different ports both in server and in the client respectively: 8081, 12345, but I always get this error message.
I have some idea about websocket and javascript, but not websocket-ruby.
I hope it will helpful you.
In nodejs.. server.js file, write below code
var WebSocketServer = require("ws").Server;
var wss = new WebSocketServer({port:8100});
console.log("websocket Server is Running...");
wss.on('connection', function connection(ws) {
// Store the remote systems IP address as "remoteIp".
var remoteIp = ws.upgradeReq.connection.remoteAddress;
// Print a log with the IP of the client that connected.
console.log('Connection received: ', remoteIp);
// Add a listener which listens for the "message" event.
// When a "message" event is received, take the contents
// of the message and pass it to the broadcast() function.
ws.on('message', wss.broadcast);
});
wss.broadcast = function(msg) {
wss.clients.forEach(function each(client) {
client.send(msg);
})
};
In javascript...
var SERVER_URL = 'ws://localhost:8100';
//instead of localhost you can also use IP address of your system
var ws;
function connect() {
alert('connect');
ws = new WebSocket(SERVER_URL, []);
// Set the function to be called when a message is received.
ws.onmessage = handleMessageReceived;
// Set the function to be called when we have connected to the server.
ws.onopen = handleConnected;
// Set the function to be called when an error occurs.
ws.onerror = handleError;
}
function handleMessageReceived(data) {
// Simply call logMessage(), passing the received data.
logMessage(data.data);
}
function handleConnected(data) {
// Create a log message which explains what has happened and includes
// the url we have connected too.
var logMsg = 'Connected to server: ' + data.target.url;
// Add the message to the log.
logMessage(logMsg)
}
function handleError(err) {
// Print the error to the console so we can debug it.
console.log("Error: ", err);
}
function logMessage(msg) {
// with the new message.
console.log(msg);
}
/** This is the scope function that is called when a users hits send. */
function sendMessage{
ws.send(msg);
};
connect();
in html use one button to send message to websocket server
<button onclick="sendMessage('Hi Websocket')">send message</button>
To the best of my knowledge, the Ruby code you presented does not start a Websocket server... what it does is initiate a server-side parser.
To start a server you need to use an actual websocket server.
ActionCable (with Rails) uses the websocket-ruby library to parse websocket events and it uses nio4r to operate the actual server.
Faye have a similar solution and em-websockets use the websocket-ruby gem with EventMachine.
Other Ruby Websocket servers include Iodine, which uses the C library facil.io. Iodine is used by the framework plezi as well as independently.
Since you were trying to run an echo server, here's a quick example using the Plezi framework (you can use it as middleware in Sinatra or Rails)...
...place the following in a config.ru file:
require 'plezi'
class WebsocketSample
# HTTP index
def index
'Hello World!'
end
# called when Websocket data is recieved
#
# data is a string that contains binary or UTF8 (message dependent) data.
def on_message(data)
puts "Websocket got: #{data}"
write data
end
end
Plezi.route '/', WebsocketSample
run Plezi.app
To run the server, call (ignore the $ sign, it marks this code as terminal code):
$ iodine
notice: Iodine requires a BSD / Unix / Linux machine, such as macOS, Ubuntu, etc'. It won't work on windows.

net::ERR_CONNECTION_REFUSED Error jQuery ajax node.js

This error happens when the date change in the date input happens very quickly. If I change the date every 2+ seconds, it works fine. But it gives the following error when the date input is changed very fast. In short, this error happens only when the next request is made right after the first one very quickly. I've spent hours and search a lot of similar issue with this error ERR_CONNECTION_REFUSED on SO and google, but no luck. Any ideas of what's causing this issue?
Also, when load the url (http://localhost:8000/svc/diary/2016-01-03) in browser, the data comes out fine, but if I reload (Ctrl + R) the url very fast, it goes to yahoo search with these terms:
http localhost 8000 svc diary 2016 01 03 diary
The Error Message from the console:
GET http://localhost:8000/svc/diary/2016-01-03 net::ERR_CONNECTION_REFUSED
send # jquery-2.2.0.js:9172
jQuery.extend.ajax # jquery-2.2.0.js:8653
(anonymous function) # idiary.js:18
jQuery.event.dispatch # jquery-2.2.0.js:4732
elemData.handle # jquery-2.2.0.js:4544
The Date form
<input class="form-control" id='ddate' type="date" name="bday">
The Ajax Call
$('#ddate').on('change', function() {
var ajaxParams = {
url: '/svc/diary/' + $(this).val(),
type: 'GET',
contentType: "application/json",
dataType:"json"
};
console.log(ajaxParams);
$.ajax(ajaxParams)
.done(function (data, textStatus, jqXHR) {
console.log("diary retrieved!")
console.log(data);
$("#diary").text(data.diary);
})
.fail(function (jqXHR, textStatus, errorThrown) {
$("#diary").text("");
console.log("failed to retrieve diary!");
console.log(errorThrown);
});
});
The backend node.js GET handler
function getDiary(req, res) {
var date = req.params.date;
util.log(mysql.format(searchQuery, [date]));
util.dbpool.query(searchQuery, [date], function (err, result) {
res.setHeader("Content-Type", "application/json");
if (err) {
console.log(err);
util.errLog(JSON.stringify(err));
res.status(500).json({message: 'summary, no results.'});
} else {
console.log(result);
result.length > 0 ? res.status(200).json(result[0]) : res.status(200).json({"ddate":date, "diary":""});
}
});
}
UPDATE: Just found out, this issue is gone when starting the node application server with
node server.js
This issue happens only when starting the node application server with pm2 or foerver
pm2 start --watch server.js
forever start --watch server.js
The issue is resolved. It was caused by using the watch flag in pm2 and forever. My app prints log statements, and the log folder is in the same level as the application folder, so whenever a log file is updated, pm2 is restarting my application server. That is why it works if I pin my application server every few seconds because the server restart only takes about a second. It gives connection refused error if I pin the server very fast, because the server is still restarting, that's why it's connection refused.
You are looking to make a cross domain request. By default server disallows this. You need to enable it on your server, and make a JSONP request. You can read about it here:
http://www.leggetter.co.uk/2010/03/12/making-cross-domain-javascript-requests-using-xmlhttprequest-or-xdomainrequest.html
What is JSONP all about?

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.

Categories

Resources