I have a web app that is running on rails 4 at localhost:3000. I am also have angularjs on client side. I have placed scoket.io.js file in my rails app public folder. From my angularjs client code, I run this code
this.connect = function (endpoint) {
if(!socket) {
socket = io.connect(endpoint);
socket.on('connect', connectHandler);
socket.on('connect_failed', connectFailedHandler);
socket.on('message', messageHandler);
socket.on('disconnect', disconnectHandler);
socket.on('close', disconnectHandler);
socket.on('nexus_disconnect', this.disconnect);
} else {
socket.socket.connect(endpoint);
}
};
I am getting error as below on my browser console.
http://localhost:3000/socket.io/1/?t=1405687049255 404 (Not Found)
Is any server other than rails server needed for socket.io?
Yes, you have to set up Node.js server.
There are several implementations of Socket.IO server in other languages, but it seems that there is no one written in Ruby.
Related
I am currently trying to run my react-native/rails app on my phone for testing purposes. I can run my sign in and log in screens fine because they do not communicate with my server until the user info is entered. When running my server i use:
$ rails s --binding=0.0.0.0
I do not receive any errors other than knowing my server is not being communicated with. This all works fine on my Android Studio Emulator as well.
// one of my fetch GET requests
export function requestCurrentUser(username, auth_token) {
return function action(dispatch) {
const request = fetch(`'http://10.0.2.2:3000'/users/${username}`, {
method: 'GET',
headers: {
"Authorization": auth_token
}
});
return request.then(
response => response.json(),
err => console.log("user error"),
)
.then(
json => dispatch(receiveCurrentUser({id: json.id, email: json.email, username: json.username})),
err => console.log("user json error"),
);
}
}
I've tried changing my Phone IP settings to a 10.0.2.2 Gateway, and using my phone's IP in my fetch request. I feel like I am missing something conceptually. Thanks in advance.
In fetch request you need to use the IP from the machine that are running the rails server,
probably your notebook and use the same network to connect your app and your rails backend api. In order to test, you can try directly access your api in your phone browser accessing http://IP_FROM_RAILS_MACHINE:3000
I am currently trying to connect our Kotlin Multiplatform Project to websockets. I would like to use ktor-websockets library to receive some updates from our backend but onfortunately when I run this code, nothing happens:
client.webSocket(
port = 80,
method = HttpMethod.Get,
host = "https://uat-betws.sts.pl",
path = "/ticket?token=eyJzdWIiOiI0ZmY5Y2E1Mi02ZmEwLTRiYWYtODlhYS0wODM1NGE2MTU0YjYiLCJpYXQiOjE2MTk4MDAwNzgsImV4cCI6MTYxOTgwMzY3OH0.oIaXH-nFDpMklp4FSJWMtsM7ECSIfuNF99tTQxiEALM"
)
{
for (message in incoming) {
message as? Frame.Text ?: continue
val receivedText = message.readText()
println(receivedText)
}
// Consume all incoming websockets on this url
this.incoming.consumeAsFlow().collect {
logger.d("Received ticket status websocket of type ${it.frameType.name}")
if (it is Frame.Text) {
Json.decodeFromString<TicketStatusResponse>(it.readText())
}
}
}
Does somebody have any experience with ktor-websockets library? There is almost no documentation so maybe I am doing something wrong.
Thank you
As the documentation says
Ktor provides Websocket client support for the following engines: CIO, OkHttp, Js.
This means that it works only on JVM/JS, you're probably targeting iOS. It's not yet supported, you can follow issue KTOR-363 for updates
For sure the team is working on it, but for now you had to implement it by yourself using expect/actual, you can check out official example
An other possible problem in your code: host shouldn't include https://, if you're using ssl, you should add an other parameter:
request = {
url.protocol = URLProtocol.WSS
}
Or use client.wss(...) - which is just a short form for the same operation
I'm trying a react native application using couchDB 2.1.1. PouchDB entry in package json looks like this:
"pouchdb": "^6.3.4",
"pouchdb-react-native": "^6.3.4",
Replication is as shown below:
const localDB = new PouchDB('employee');
const remoteDB = new PouchDB('http://username:password#localhost:5984/employee');
localDB.replicate.from(
remoteDB,
(err, response) => {
if (err) {
return console.log(err);
}
},
);
I get following error:
{"code":"ETIMEDOUT","status":0,"result":{"ok":false,"start_time":"...","docs_read":0,"docs_written":0,"doc_write_failures":0,"errors":[],"status":"aborting","end_time":"...","last_seq":0}}
Almost all the times this works fine when I run the app in debug mode. Tried ajax timeout as shown here PouchDB ETIMEDOUT error. This didn't work. Is there something that I'm supposed to look in my code? Please help.
Had the same issue, the following fixed it for me:
Use your PC ip address instead of localhost
Configure your firewall
to allow connections on port 5984 OR just disable it (Not
recommended)
I just started building me server using socket.io for both my client and Node.js server side.
I'm writing an Objective-c project so i walk through the process of adjusting my project to use Swift alongside with Objective-c which was a pain but it seems to be ok now.
The thing is, when i try to do a simple connect to my server, which prints to log on each connection, nothing happens.
This is the code for the server (Taken from here):
var fs = require('fs')
, http = require('http')
, socketio = require('socket.io');
var server = http.createServer(function(req, res) {
res.writeHead(200, { 'Content-type': 'text/html'});
}).listen(8080, function() {
console.log('Listening at: http://localhost:8080');
});
socketio.listen(server).on('connection', function (socket) {
console.log('Connected');
socket.on('message', function (msg) {
console.log('Message Received: ', msg);
socket.broadcast.emit('message', msg);
});
});
Super simple, really nothing to it.
And the Objective-c code for my client which is even more simple:
- (void) connect
{
SocketIOClient* client = [[SocketIOClient alloc]initWithSocketURL:#"http://127.0.0.1:8080/" options:nil];
[client connect];
}
But i can't see nothing on my console except the Listening at: http://localhost:8080 message.
I can't seem to find what i'm doing wrong here, and the fact that the swift debugging is horrible in this combined project, i can't really fully go through the socket.io debugging myself (but i'm pretty sure nothing's wrong with their code)
Any help would be much appreciated.
plz confirm, if you are using the simulator for iOS testing. For device, you need to assign public address to your NodeJS server, and then need to use it's ip in iOS Codebase.
I had used https://github.com/pkyeck/socket.IO-objc during my last project and it worked like a charm.
For simulator, your code should ideally work.
So Im messing around with developing a spotify app, trying to get it to talk to my local rails application API. I cant get anything other than a req.status 0 when I try it.
I think its either a problem with the spotify manifest.json file, not allowing the port:3000 to go on the url you set in required permissions, but it also says the following in their documentation.
https://developer.spotify.com/technologies/apps/tutorial/
If you need to talk to an outside web API you're welcome to, as long as you abide by the rules set in the Integration Guidelines. Please note that when talking with a web API, the requests will come from the origin sp://$APPNAME (so sp://tutorial for our example) - make sure the service you are talking to accepts requests from such an origin.
So, Im not sure if rails is set to not allow this sort of thing, or if its an issue with the putting the port into the required permissions, but my request
var req = new XMLHttpRequest();
req.open("GET", "http://127.0.0.1:3000/api/spotify/track/1.json", true);
console.log(req);
req.onreadystatechange = function() {
console.log(req.status);
console.log(req.readyState);
if (req.readyState == 4) {
if (req.status == 200) {
console.log("Search complete!");
console.log(req.responseText);
}
}
};
req.send();
Always returns status 0 where as their example:
var req = new XMLHttpRequest();
req.open("GET", "http://ws.audioscrobbler.com/2.0/?method=geo.getevents&location=" + city + "&api_key=YOUR_KEY_HERE", true);
req.onreadystatechange = function() {
console.log(req.status);
if (req.readyState == 4) {
console.log(req);
if (req.status == 200) {
console.log("Search complete!");
console.log(req.responseText);
}
}
};
req.send();
Will return a 403 response at least. its like the request is not being made or something?
Anyone have any idea what might be going on?
Much appreciated!
When talking to external services from a Spotify App, even if they're running on your local machine, you need to make sure that two things are in place correctly:
The URL (or at least the host) is in the RequiredPermissions section of your manifest. Port doesn't matter. http://127.0.0.1 should be fine for your case.
The server is allowing the sp://your-app-id origin for requests, as noted in the documentation you pasted in your question. This is done by setting the Access-Control-Allow-Origin header in your service's HTTP response. People often set it to Access-Control-Allow-Origin: * to allow anything to make requests to their service.
Thanks for help, I got it figured out, I think it was multiple things, with one main Im an idiot moment for not trying that earlier
First off, I had to run rails on port 80, as obviously if Im accessing my site from 127.0.0.1:3000, thats not going to work if spotify app is requesting 127.0.0.1 unless I can load that directly in the browser, which you cannot unless you run on 80. That is done via
rvmsudo rails server -p 80
Need to use rvmsudo because changing port requires permissions.
Next I had to set access controll allow origin as noted above, that can be done in rails 3 by adding before filter to your app controller as follows.
class ApplicationController < ActionController::Base
logger.info "I SEE REQUEST"
before_filter :cor
def cor
headers["Access-Control-Allow-Origin"] = "*"
headers["Access-Control-Allow-Methods"] = %w{GET POST PUT DELETE}.join(",")
headers["Access-Control-Allow-Headers"] = %w{Origin Accept Content-Type X-Requested-With X-CSRF-Token}.join(",")
head(:ok) if request.request_method == "OPTIONS"
end
end
Finally, and most importantly (sigh), you cant just righclick and reload your spotify app when you make changes to your manifest file, exit spotify completely and restart it!