Use Firefox OS as web server - webserver

For an art project, I'd like to have multiple distributed devices that can output sound. Firefox OS devices seem optimal. They bring the necessary hardware and I know HTML and JS very well. But I also need a control web server.
From my understanding, a Firefox OS device can act as an WiFi access point ("Share Internet"). However, it cannot act as a small web server for other devices that join the network – without any internet connection. The APIs for native apps seem just not to be powerful enough.
But maybe I am mistaken (I would like to be). So, is a Firefox OS device able to run as a small web server?

httpd.js did not work out-of-the-box for me. But it brought me on the right track. I then found this and after a little bit of tweaking and updating of the code, I got a super-simple server solution.
function startListen(){
console.log("Initializing server");
var socketServer = navigator.mozTCPSocket.listen(8080);
socketServer.onconnect = function(conn){
console.log("connected", conn, conn.ondata);
conn.ondata = function(ev){
console.log("Got request: ", ev);
conn.send("Ok. Got client on port " + conn.port);
conn.close();
};
conn.onclose = function(ev){
console.log("Client left:", ev);
}
};
socketServer.onerror = function(ev){
console.log("Failed to start: ", ev);
};
}
startListen();
The tcp-socket permission is needed.
With this code, I was able to start this in the Firefox OS simulator, direct my browser to open http://localhost:8080 and get an answer and logs in the console.
PS. This also works on a real device. Unfortunately, a separate access point is needed. While Firefox OS can work as a hotspot itself, it can neither be client or server in that mode (outgoing connections are not routed properly and incoming connections are refused).

You should try httpd.js. This library is for FirefoxOS 2.0.
// create a server object
server = new HttpServer();
// configure /sdcard/public as document root
server.get("/", "/sdcard/public");
// launch on port 3000
server.start(3000);

I don't think that you need a server for this task, you can do master-slave communication with WebRTC and handle the execution of the sound client side.

I recently wrote an article on the Mozilla Hacks blog demonstrating how to implement this:
Embedding an HTTP Web Server in Firefox OS

Related

Configure flutter web app to broadcast data to any subscribed listeners with sse

I am currently developing a flutter web app, and would like to implement a feature to broadcast json data to any listeners/subscribers.
To give more detail:
The web app has a flutter front end server running on localhost. A user will be able to fetch some JSON data from an external backend server using a simple GET request.
Once the app has loaded the JSON data, it will need to broadcast it down an SSE stream to any listeners. This listener will be a seperate flutter application.
Now, I understand that there a few problems with this.
Firstly, Flutter web doesn't support dart:io... Fine - I have managed to get round this by using the universal_io dart package instead of dart:io. The api is the same, and after solving a few CORS errors, works a charm for the GET requests in the first bullet above. This means that the json data can be successfully loaded into the Flutter app.
(universal_io dart package -> https://pub.dev/packages/universal_io).
The next issue is with SSE. Part one of this is that there is not much documentation on implementing an SSE server in Flutter - only a client that can listen. However, I have managed to find a solution in the sse dart package example app...
import 'package:shelf/shelf_io.dart' as io;
import 'package:sse/server/sse_handler.dart';
/// A basic server which sets up an SSE handler.
///
/// When a client connnects it will send a simple message and print the
/// response.
void main() async {
var handler = SseHandler(Uri.parse('/sseHandler'));
await io.serve(handler.handler, 'localhost', 0);
var connections = handler.connections;
while (await connections.hasNext) {
var connection = await connections.next;
connection.sink.add('foo');
connection.stream.listen(print);
}
}
(sse dart package -> https://pub.dev/packages/sse)
(continued) Usually, this would be a fine solution, and it could probably be modified a little for implementation within a flutter app. However, the shelf_io.dart package, used to spin up the server, depends on the dart:io package, which doesn't work with Flutter Web.
The other thought is - why do we need to set up a new server connection (with io.server(...)) when the flutter web app is already running on its own localhost server? This begs the question: Is there a way to add this sseHandler endpoint onto the localhost server that the Flutter Web app is running on?
All in all, what i'm trying to ask is:
Is there a way for a Flutter Web App to send SSE messages to a collection of listeners?
At the moment I've hit a bit of a deadend with research on this so if anyone had any bright ideas on a potential solution then the help would be greatly appreciated. Thanks :)
Side Note: Obviously this is something that could very easily be done with Java, J2Html and so on, but wheres the fun in giving up just like that... On the other hand, maybe flutter web is still just too new to support stuff like this?

How can i use sockets with Flutter web

I'm trying to make a connection between a socket server written in Python using socketio to a client made with Flutter Web.
I tested various socket packages like adhara_socket_io and flutter_socket_io and nothing worked. I tried the same code snippets on Android and they didn't work too.
I kept searching and i found this code snippet. It uses the Socket class from the dart.io package.
Socket socket = await Socket.connect('192.168.2.190', 7003);
print('connected');
// listen to the received data event stream
socket.listen((List<int> event) {
print(utf8.decode(event));
});
// send hello
socket.add(utf8.encode('hello'));
// wait 5 seconds
await Future.delayed(Duration(seconds: 5));
// .. and close the socket
socket.close();
This one connected to the Python server and sent the data from Android but when i tested it from Web i didn't connect.
Is there some things extra i need to add for it to work on Web?
Or in the worst case, is there another way to do what i want to do, my goal is to display a video feed in a website. The video is actually a bunch of images taken from Python, there is some machine learning that will be performed on them and i want to send them over socket and each image is displaying as soon as it is received so it looks like a video feed. (Similar thing was done using React)
dart.io package is not compatible with flutter web. And I suppose As pskink suggested websockets is the way to go. You can use HtmlWebSocketChannel from the web_socket_channel package as documented here. I have used this package and can confirm it works well in flutter web.
In your case should be using something as follows.
var channel = HtmlWebSocketChannel.connect("ws://192.168.2.190:7003");
But do note that this is not inter operable with regular flutter app. If you aim to target both android and flutter web, then you should handle this channel creation conditionally depending on target you are building it for and decide between HtmlWebSocketChannel or IOWebSocketChannel to create the connection. If you are interested you can use a conditional stub based implementation as suggested in this post*.
* Note: its my post. :)

UWP server socket always listening

I implemented an UWP Server Socket following the sample here and it correctly works.
Now I want to make the app able to continuously accept requests, but I expect that when the app is suspendeded and a client sends a request, the server is not able to respond. If I am correct, what is the best way to avoid this status change? If possible, I would prefer a solution with Extended Execution instead of implementing a Background Task, but I don't know if the following code in the OnSuspending method is enough to keep the app in the Running status:
var newSession = new ExtendedExecutionSession();
newSession.Reason = ExtendedExecutionReason.Unspecified;
newSession.Revoked += SessionRevoked;
I saw people calling a "LongRunningWork()" function in other samples, but in my case the code to execute is already defined in the code-behind of the view as shown in the link above, so I would like simply keeping the app always running. Keep in mind that it is a LOB application, so I don't have Store limits.

Unity WWW cancel request and close socket/connection

In the latest (4.5.4) version of Unity3D, is it possible to cancel a pending WWW class (HTTP) request and have it close the socket/connection? I've tried myWWWObject.Dispose, at least in the editor play mode, and it isn't working.
This forum post on Unity forums has conflicting answers. One person says it works, then another says it doesn't but the answer they provide makes me think they only care about resuming the coroutine and not closing the actual connection.
I'm writing a game that needs to work on iOS, Android and Facebook Canvas (Web Player), and I'm using long polling to my own server. There are times when I want to cancel an existing poll and post a new one. In some cases (kind of odd behavior but possible) the user could cause that to happen over and over many times in a row. I don't want all of those connections to stay open on my server, or client side, even though it is easy for my code to ignore any result/response.
I can probably work around this with design changes, but would rather not, if there is a robust way to close/cancel/abort/stop the request. I'm pretty sure all of the 3 platforms I need to support have ways to do this natively, but not sure I want to use native plugins instead of WWW class.
I'm not quite sure but I think that when you mean to close the socket connection you are lowering down to the TCP/IP or UDP layer. Then, you are not in control of this layer from a WWW gameObject as far as I know. So technically even if you cancel out the 'transfer', the socket will have to wait for a TCP/IP timeout to be dropped by the OS... I think...
I found this link that might shed some light at your particular issue: http://answers.unity3d.com/questions/676443/wwwdispose-doesnt-work.html
Still I think that .Dispose() might still not close the actual socket like you want. Only in the case that you are directly handling via Thread, TcpListener and TcpClient you are allowed to issue an actual socket close().
Like for example:
TcpListener myTcpListener;
TcpClient myTcpClient;
void OnApplicationQuit()
{
try
{
myTcpClient.Close();
isTrue = false;
}
catch(Exception e)
{
Debug.Log(e.Message);
}
// You must close the tcp listener
try
{
myTcpListener.Stop();
isTrue = false;
}
catch(Exception e)
{
Debug.Log(e.Message);
}
}

if basic, sample GWT app takes 30sec to load in browser, is that normal? will real apps take 2 mins?

I have a decent machine capable of running 64 bit Windows 7. So how come any time I stop a small sample GWT app in "development mode", edit it and restart it it takes 30 sec to become responsive in the browser, both in latest Firefox and latest Chrome?
Is that sort of molasses-based edit-compile cycle just the normal, expected thing for GWT developers nowadays?
Will it get much worse for more realistic apps or is the whole of those 30 sec just the framework overhead, and my own code would not make it much more bloated than that any time soon?
Can this problem be alleviated by using some other "mode" or by whatever other tweak solution?
Do Google people have much faster machines than I do on which this is less of a pain or do they suffer like the rest of us?
During development, a GWT application can be run in different modes, and there's often a bit of confusion about when it's necessary to
restart the server,
reload the server,
refresh the browser,
or just click somewhere in the web page.
Let's take a step back and look at all the differences between Development mode/Production mode on the one hand, and "With Debugger"/"Without Debugger" on the other hand. Of course, everybody using GWT has already heard of them...
Mode
Development mode
Runs the client side with a special browser plugin that attaches to a code server. You can always identify this mode easily by looking at the URL - it will contain something like ?gwt.codesvr=127.0.0.1:9997
The main advantage of Development mode is, that it doesn't require you to compile your code to JavaScript first - it runs the client side as Java bytecode in the code server. This is basically a JavaScript emulation - but it's so close, that most people don't notice the difference anymore (some even believe, that GWT compiles Java to JavaScript in Development mode, which is not the case.)
Since the code is run as Java bytecode, this mode also allows you to attach a debugger for the client side code, as we will see a little bit below (but you don't have to!)
Production mode
Runs the client side as compiled JavaScript. Before you can use it, you have to use the GWT Java to JavaScript compiler first (often known as gwtc, or "the one with the
icon")
After it's finished (takes a while!) just start the GWT embedded server like in development mode, but this time remove the ?gwt.codesvr=127.0.0.1:9997 from your URL. (Alternatively, you can deploy the war to a separate server (e.g. Tomcat), and run it from there.)
The advantage here is, that a) you can test the real compiled result, and b) that browser refresh is very much faster than in Development mode.
Launching
"Without Debugger"
You can simply run the application without attaching a debugger (that's possible both in Development and Production mode). Use "Run As...", if you use Eclipse.
In Development mode, this means that you run a web server (embedded Jetty, usually on port 8888) and a code server (usually port 9997). In Production mode, you don't need the code server.
If you have client side changes, they will be reloaded when you refresh the browser. This is relatively fast - you don't have to restart the (code) server. But it's not as immediate as with a Debugger.
If you have server side changes, you will have to do a server web application reload (in Eclipse, you use the small yellow reload icon in the Development view) This is much faster than a full server restart, but once again, it's not as immediate as with a Debugger!
"With Debugger"
Both in Development and Production mode, you can run the application with an attached debugger. Use "Debug As...", if you use Eclipse.
For Development mode, the debugger attaches both to the client and the server side of the code - whereas in Production mode, it can only attach to the server side!
If you have client side changes with an attached debugger, code changes will take effect immediately, so all you have to do is to click somewhere in your web page that causes the code to run.
If you have server side changes with an attached debugger, likewise, code changes will take effect immediately, so all you have to do is to perform some action that causes the corresponding server call.
All of this is extremely fast, but the drawback is, that Java debuggers can cope only with certain kinds of code changes. If you have more severe changes, the debugger will exit, and you'll have to restart the server (I'm still looking for a way to just reload and reattach in this case - I think it should be possible, but does anyone already have a working solution?)
Also, with debuggers, you'll have to be careful with the state of your application. Remember, that the changes to your code won't re-evaluate the existing state!
So you basically have four combinations
Development mode without Debugger
Client change: Use browser refresh (medium)
Server change: Reload server (fast)
Development mode with Debugger
Client change/server change: Just click on the web page (very fast). Restart server, if this fails (very slow).
Production mode without Debugger
Client change: Recompile, then refresh browser (very slow)
Server change: reload server (fast)
Production mode with Debugger (for the server side)
Client change: Recompile, then refresh browser (very slow)
Server change: Just click on the web page to cause a new server call (very fast). Restart server, if this fails (very slow).
Additional differences:
A simple browser refresh in Production mode is much faster than in Development mode.
GWT-RPC in Production mode is much faster than in Development mode.
Each combination has its own benefits and drawbacks for development speed and convenience. I like to use all of them, depending on the situation.
This post has become a bit long, but I have seen lots of questions around this topic, and I wanted to write it all down in one place. Thanks for reading :-)
I guess my answer is in the form of a question, "Are you sure you're really needing to restart at all?"
Assuming you're running it hosted within the browser (which it sounds like you are) then most changes are "hot" almost as soon as you've finished them. I spent yesterday doing all kinds of changes to the main code file in a module and didn't have to restart the server for any of them.
I often had to reload the page within the browser to see the changes, but that's a different issue.
In GWT development mode every time you reload a page the dev server recompiles the GWT app's source. This enables you to just do some changes to your GWT code and just reload the page in browser to see the changes - no need to restart the dev mode server.
When you deploy your app on production server you deploy already compiled javascript files. So the delay you will see will be time to load those pages.