Flutter Socket.IO cannot connect to server, but browser works fine - flutter

Was going to use Socket.IO for authorizing in a flutter application, but it wont work on anything other than localhost:
String serverURL = "https://example.awsapprunner.com";
IO.Socket socket = IO.io('$serverURL/client', <String, dynamic>{'transports': ['websocket']});
checkUserExists(String phoneNum, context) {
socket.connect();
socket.emit('login', phoneNum);
socket.on('login_error', (res)=> {
log("new user"),
});
socket.on('session-started',(sid)=>{
log("old user!"),
});
}
The app won't even connect to the socket so anything after socket.connent() never runs.
Here's what I have tried
'autoConnect': true
replacing 'https' with 'wss' or 'ws'
removing 'https://' altogether
Different Cloud Services (AWS, GC, Azure)
local server (works and connects perfectly fine)
connecting to the server via browser (also works perfectly fine)

Related

stompjs socket connection in kubernetes

I'm using stompjs, sock-client to establish a socket connection from a react-app to a springboot app. Both front-end and back-end are hosted in the same kubernetes cluster, but in different namespaces. Both are load balanced.
When running locally, this works fine:
UI:
const endpoint = 'http://localhost:8080/websocket';
let socket = new SockJs(endpoint);
stompClient = StompJs.over(socket);
stompClient.connect({}, this.onStompConnectSuccess, this.onStompErrorCallback);
Server side:
#Override
public void registerStompEndpoints(StompEndpointRegistry registry) {
registry.addEndpoint("/websocket").setAllowedOrigins("http://localhost:3000").withSockJS();
}
However what URL do i use for the hosted versions? Setting the load-balanced URLs gives an error
Whoops! Lost connection to https://load-balanced-url/websocket

How to connect wss in flutter web?

I try to connect a socket-io with flutter. Before, our server-side developer give me an URL without SSL-Certificate and everything is worked. But now, our server has SSL-Certificate, I can't connect to that socket-io. This is my code to connect:
Socket socket = io(
'wss://server-address',
OptionBuilder()
.setTransports(['websocket'])
.disableAutoConnect()
.build());
socket.connect();
socket.onConnect((_) {
print('socket connect');
});
socket.onConnectError((data) => print('socket error = ' + data.toString()));
I get this error:
socket error = {msg: websocket error, desc: null, type: TransportError}
I try to deploy my web application on a secure host like firebase but still have problems. In inspect of firefox, I also see this error:
Firefox cant establish a connection to the server
How to fix this problem? How to connect to secure socket-io address in flutter web?

flutter app can not connect to a webSocket

I am building a flutter app which needs to connect to the server and exchange data using websocket. The server is in JAVA and using SockJs and Stomp to implement this functionality.
I am using Stomp dart client and webSocket packages from pub.dev/packages.
This is the part of my code where I am trying to connect :
clientConnect() async {
String cookie = await storage.read(key: "cookie");
final stompClient = StompClient(
config: StompConfig(url: 'ws://192.168.0.13:8080/....', onConnect: onConnect,
webSocketConnectHeaders: {"cookie": cookie }));
stompClient.activate();
}
The problem I am facing is, my flutter app is not able to connect to the server and throws the this error.
WebSocketException: Connection to 'http://192.168.0.12:8080/....' was not upgraded to websocket
Late answer (maintainer of the stomp package):
Since you seem to be using StompJS on the java-side you need to use the special StompJS config in the client. Here is the example from the documentation:
https://pub.dev/packages/stomp_dart_client#use-stomp-with-sockjs
StompClient client = StompClient(
config: StompConfig.SockJS(
url: 'https://yourserver',
onConnect: onConnectCallback
)
);

Connecting Aurelia with backend API

Context: I'm starting a new project for my company. It's been many years since I've done some web development and decided to build it using the latest platforms (so I'm a still new to all of this).
Current stack:
Aurelia frontend (running on localhost:9000)
Backend REST API using ExpressJS (running on localhost:8000)
PostGreSQL database running on AWS, providing data for the backend
Question: I can't seem to connect my frontend with my backend properly.
Here is my code:
import {inject} from "aurelia-framework";
import {HttpClient} from "aurelia-http-client";
#inject(HttpClient)
export class Login {
constructor(httpClient){
this.http = httpClient;
}
signIn() {
const url = 'http://localhost:8000/api/user/demo/test';
this.http
.get(url)
.then(data => {
console.log("data");
console.log(data);
})
.catch(error => {
console.log('Error getting ' + url);
console.log(error);
});
};
}
This always end up in the catch block, with a "response: ProgressEvent"
If I put the url in the browser I get a proper JSON:
{"status":"success","data":[],"message":"Retrieved ALL users"}
The code above only works for 'local' content, i.e. localhost:9000. As soon as I need content from somewhere else I get this error. What am I missing?
I think that CORS is not allowing you to access localhost:8000 from localhost:9000. To solve this, you should enable your ExpressJS server to accept CORS requests from localhost:9000 (or all hosts using a wildcard "*").
Look into these resources:
https://enable-cors.org/server_expressjs.html
https://github.com/expressjs/cors
Or search Google for 'expressJS cors'.

Can I set up socket.io chat on heroku?

I have a simple socket.io chat application which I've uploaded to one of the new Heroku 'cedar' stacks.
Now I almost have everything working but I've hit one stumbling block. On my localhost, I open a connection to the socket server from the client with:
// lots of HTML omitted
socket = new io.Socket('localhost', {port: 8888});
But on Heroku, I obviously must substitute something else in for these values.
I can get the port from the process object on the server like so:
port = process.env.PORT || 8888
and pass that to the view.
But what do I substitute for 'localhost'?
The correct way according the article on heroku is:
io.configure(function () {
io.set("transports", ["xhr-polling"]);
io.set("polling duration", 10);
});
socket = new io.Socket();
This ensures that io.Socket won't try to use WebSockets.
I was able to get Socket.IO v0.8 to work on Heroku Cedar by doing the following:
Within the Express app (in CoffeeScript in my case):
app = express.createServer();
socket = require("socket.io")
...
io = socket.listen(app);
io.configure () ->
io.set("transports", ["xhr-polling"])
io.set("polling duration", 10)
io.sockets.on('connection', (socket) ->
socket.on('myaction', (data) ->
...
socket.emit('result', {myData: data})
### The port setting is needed by Heroku or your app won't start
port = process.env.PORT || 3000;
app.listen(port);
And within the front-facing Javascript of your application:
var socket = io.connect(window.location.hostname);
function sendSocketRequest() {
socket.emit('myaction', $("#some_field").val());
}
socket.on('result', function(data) {
console.log(data);
}
Helpful links:
Heroku Node help
Heroku Socket.IO help
This has now changed as of Oct 2013, heroku have added websocket support:
https://devcenter.heroku.com/articles/node-websockets
Use:
heroku labs:enable websockets
To enable websockets and dont forget to remove:
io.configure(function () {
io.set("transports", ["xhr-polling"]);
io.set("polling duration", 10);
});
After trying every combination under the sun I finally just left it blank. Lo and behold that works perfectly. You don't even need the port.
socket = new io.Socket();
I was also having this problem on heroku. I was able to make it work using the hostname "myapp.herokuapp.com" (or simply window.location.hostname, to work both local and in production) and setting the port to 80. I'm using SocketIO 0.6.0.
Wouldn't you just put your actual hostname?
2011-06-25T21:41:31+00:00 heroku[router]: Error H13 (Connection closed without response) -> GET appxxxx.herokuapp.com/socket.io/1/websocket/4fd434d5caad5028b1af690599f4ca8e dyno=web.1 queue= wait= service= status=503 bytes=
Does this maybe mean the heroku router infront of the app is not configured to handle web socket traffic?
[update]
It would appear as of 6/22/2011 the answer is yes... heroku does not support socket.io see this post: http://blog.heroku.com/archives/2011/6/22/the_new_heroku_2_node_js_new_http_routing_capabilities/