How to run dart http server over a remote server - flutter

I have a server of Ubuntu 20.04, and I've successfully run a apache server and I can visit the site with ip address (or domain) from the Internet. But with dart it could be visited from the server with 127.0.0.1/localhost but I could not visit the site from the Internet. How could i fix the problem...?
With dart
Chrome Preview (Empty Response)
zsh Preview (works well)
dart run
With Apache
Chrome Preview
systemctl start apache2
What i have ever tried
close the apache server and change dart server port to 80, not working
add ports config in firewall
Code
No dependency, all-code-in-a-file:
dart create tmp
cd tmp
vi bin/tmp.dart
dart run
import 'dart:io';
void main(List<String> arguments) {
print('Hello world!');
HttpServer.bind(InternetAddress.loopbackIPv4, 80).then((server) {
server.listen((request) {
request.response.statusCode = 200;
request.response.write("---");
request.response.close();
});
});
}

Thanks to #julemand101, it's all my faults…… Simply change InternetAddress.loopbackIPv4 to InternetAddress.anyIPv4 works fine!

Related

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

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)

Running flutter web app locally without android studio

I have a flutter app using Firebase's cloud firestore. I've done the web build and running it on Chrome through Android Studio works well. I would like to share my web app progress to my client but don't want to host it (because it's not finished yet). Hence I'd like to find a way to run it locally the same way you can do it with Android Studio but without needing to install Android Studio (and hopefully not requiring to install flutter either), so that I can send the build file to my client and they can run it in their machine (with a script to start the web server locally and run the web app).
I have tried the following script included inside the web build folder (where the index.html is)
from BaseHTTPServer import BaseHTTPRequestHandler, HTTPServer
from httplib import HTTPResponse
from os import curdir,sep
#Create a index.html aside the code
#Run: python server.py
#After run, try http://localhost:8080/
class RequestHandler(BaseHTTPRequestHandler):
def do_GET(self):
if self.path == '/':
self.path = '/index.html'
try:
sendReply = False
if self.path.endswith(".html"):
mimeType = 'text/html'
sendReply = True
if sendReply == True:
f = open(curdir + sep + self.path)
self.send_response(200)
self.send_header('Content-type', mimeType)
self.end_headers()
self.wfile.write(f.read())
f.close()
return
except IOError:
self.send_error(404,'File not found!')
def run():
print('http server is starting...')
#by default http server port is 80
server_address = ('127.0.0.1', 8080)
httpd = HTTPServer(server_address, RequestHandler)
try:
print 'http server is running...'
httpd.serve_forever()
except KeyboardInterrupt:
httpd.socket.close()
if __name__ == '__main__':
run()
But when opening http://localhost:8000 on Chrome I get a blanc page and the console shows the errors:
Failed to load resource: net::ERR_EMPTY_RESPONSE main.dart.js:1
Failed to load resource: net::ERR_EMPTY_RESPONSE manifest.json:1
Failed to load resource: net::ERR_EMPTY_RESPONSE :8080/favicon.png:1
I also tried NPM local-web-server by running ws --spa index.html but just getting a ERR_EMPTY_RESPONSE response.
This is what I have in my build/web after running flutter build web:
How can I create a local server where I can host my web app locally and run it locally without hosting it on the internet?
as you mentioned in the comment here you go.
Create a file app.js with the following:
const express = require('express')
const app = express()
const port = 8000
app.get('/', (req, res) => {
console.log('getting request')
res.sendFile('website/y.html',{root:__dirname})
})
app.use(express.static(__dirname + '/website'))
app.use((req, res)=>{
res.redirect('/')
})
app.listen(port, () => {
console.log(`app listening at http://localhost:${port}`)
})
Here my website files exist at website folder and my entry point is y.html.
Set the static file directory (your website page) and then serve the .html for the root request
example project: https://github.com/ondbyte/website
Finally, to run it open terminal and move to the root folder. Then do
npm init
npm install express --no-save
node app.js
Here is the more simpler way. NO NEED to setup server
open your Build/web folder in vscode.
install Live server Plugin in vscode.
hit Golive Button
Here you go your flutter web app would be running locally without android studio.

Is it possible to send messages over UDP/TCP from flutter application to .NET application?

I am trying to figure out how to send data over UDP/TCP from my flutter application to my server which has .net applications which listen for UDP and TCP . I searched about it and I found that there is a package named web_socket_channel and I tried that it is working with the testing server ws://echo.websocket.org but when I replace the echo.websocket.org with my server IP address or domain name it doesn't work even i am not getting any errors back so I couldn't figure out what's going on. Is there something wrong? or am i doing something wrong? Can someone help me with my demo code :
WebSocketChannel channel;
String text = "";
void sendSocket() {
String message = "message_text"
if(message.isNotEmpty)
channel.sink.add(message);
}
getStreamData() {
channel.stream.asBroadcastStream().listen((event) {
if (event != null)
print(event);
});
}
#override
void dispose() {
channel.sink.close();
super.dispose();
}
#override
void initState() {
try {
channel = IOWebSocketChannel.connect(
'ws://127.0.0.1:8889');
getStreamData();
super.initState();
} catch (e) {
print(e.toString());
}
}
I appreciate your help. Thanks you so much.
First, make sure that your server is running and available to connect.
For this problem go through all steps mentioned below:
1. Check your server is running and the app is listening to a specific port on which you are sending data
2. Check the server IP address and Port number
3. Make ping from the command prompt using "ping serverName/IP"
4. Make sure you can connect using telnet from command prompt "telnet serverName/IP portNumber"
(if telnet command doesn't work means your telnet client is not installed/enabled then
check how to enable telnetClient)
1st Solution
if everything works well then try this plugin flutter_socket_plugin or you can write your own code for socket like #Richard Heap suggested.
2nd Solution
Excellent blog on Network Socket Programming for dart: Reference Link
You can also use RawDataGramSocket for the UDP sockets refer to this thread
Socket API for TCP sockets visit this thread

FiddlerCore Https Firefox Certifcate installation and Trust

I am playing with Fiddler core , trying to set up with a proxy and check Https traffic. For Chrome and Internet Explorer fiddler have great support:
if (!CertMaker.rootCertExists())
{
if (!CertMaker.createRootCert())
return false;
if (!CertMaker.trustRootCert())
return false;
}
Anyone knows what to do with Mozilla ? How to install certificate there ?
There's nothing in Fiddler/FiddlerCore itself that will do this. You can easily start the process from a Firefox extension (see overlay.js in Fiddler's install folder):
var certdb = Components.classes["#mozilla.org/security/x509certdb;1"].getService(Components.interfaces.nsIX509CertDB);
var file = Components.classes["#mozilla.org/file/directory_service;1"].getService(Components.interfaces.nsIProperties).
get("Desk", Components.interfaces.nsIFile);
file.append("FiddlerRoot.cer");
try {
alert("On the following screen, tick the first checkbox: 'Trust this CA to identify websites.'");
certdb.importCertsFromFile(null, file, Components.interfaces.nsIX509Cert.CA_CERT);
} catch (e) { alert("Trust function returned:\n\n" + e); }
From outside Firefox or to bypass all prompts, you'd need to poke their API; see e.g. How to add a trusted Certificate Autority to Firefox with JSS shows one approach.

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/