Running a Debug HTTP Server on an Actual Smartphone
Hello. I'm Hirayama from the Technology Department.
In this article, I explore whether running an HTTP server on an actual smartphone, so that it can be accessed from a browser on a PC or elsewhere, could make development more efficient.
That said, I haven't actually used it on a large-scale product yet, so please treat it strictly as a sample.
What I made
I implemented an HTTP server inside a Unity app running on a smartphone, and accessed it from a browser on a PC on the same network.
In this example I prepared a file uploader, and the assets are swapped as soon as a file is received. In the video above, I'm swapping an image, a sound, and a json file containing the rotation speed.
Motivation
Put simply, the motivation is that when I change something on the PC, I want it to show up on the smartphone in my hand as quickly as possible.
On a product called Tokyo Prison that I worked on before, to get any change onto an actual smartphone you had to go through one of the following procedures:
- Make the change in the UnityEditor, put it on GitHub, build with Jenkins, send it to the phone and run it
- Put the assets on GitHub, run asset bundle generation on Jenkins, stand up a server that includes them, and access it from the device
- Edit the Google Sheet, pull that change into GitHub, stand up a server, and access it from the device
- Edit the Google Sheet, and have the device read it directly and apply it
The first is for code and built-in assets, the next is for pictures and sounds, and the last two are for parameters and text. The first three go through GitHub and Jenkins, so they take many steps and a lot of time. The last one is direct, so it's efficient, but as I recall this flow was only in place in a limited number of places, and it could have been troublesome if several people had wanted to edit the same sheet.
If we're talking only about iteration speed and several people working in parallel, it seems better to create whatever data you can on your own machine, and to put it into GitHub only once it's working nicely on the device. For example, if an artist is fixing a picture,
- Fix it
- Save, and it shows up on the phone in your hand
is probably the shortest path. As a first step toward this, the artist's PC and the phone need to be able to talk to each other directly so the data can be applied. That's what I tried here.
Design
When sending data from the PC to the phone, you have to choose which side acts as the server.
- The PC acts as the server
- The phone polls, or you do something on the phone to pull in the changes.
- The phone acts as the server
- The PC uploads on save, and the phone applies what it receives.
The former is easy to implement. There are any number of HTTP servers that run on a PC, and a Mac comes with Apache from the start. An ordinary smartphone game already uses a mechanism for fetching data over HTTP, so almost no additional implementation is needed. Download the updated assets, save them in, say, persistentData, and if they're already loaded into memory, discard and reload them, and you're done.
However, I have a bad feeling about the part where you "have artists and game designers set up their PCs to run an HTTP server". Explaining it and troubleshooting it doesn't look like light work. The implementation effort is a one-time thing, but the operational effort goes on forever, so "zero preparation on the user's PC" is probably ideal.
So I decided to make the client side the server.
- When the client starts on the phone, the HTTP server starts
- The IP appears on the screen
- Enter that IP in the PC's browser and a site appears
- Do operations such as uploading there
- It shows up on the phone
That's the flow. No preparation is needed on the PC, so it should be easy for the people using it. Having to upload through the browser is a bit of a hassle, but when the flow is to fix a particular file and apply it, fix it and apply it, over and over, you only have to select the file once. If all it takes is "press the send button every time you save", that's acceptable enough.
Of course, ideally it would be "save and it's sent automatically", which can be achieved by accessing the phone over HTTP from a plugin for Photoshop and the like. But you'd need to make one for every piece of software you use, so whether it really pays off probably depends on the team's situation and size.
Implementation
The HTTP server side
C#'s standard library has a handy feature called HttpListener. I used it to make a class called DebugServer.
public DebugServer(int port)
{
if (!HttpListener.IsSupported)
{
return;
}
listener = new HttpListener();
listener.Prefixes.Add("http://*:" + port + "/");
...(omitted)...
listener.Start();
listener.BeginGetContext(OnRequestArrival, this);
}
The class name is DebugServer, and the constructor stands up the server. It instantiates an HttpListener, calls Prefixes.Add() to specify the URL patterns to accept, calls Start(), and then BeginGetContext(). BeginGetContext() is given a callback (OnRequestArrival), which is called when a request comes in. It could be written more cleanly with async/await, but I wrote it the old way so it can also be used with older Unity versions.
And the callback looks like this.
void OnRequestArrival(IAsyncResult asyncResult)
{
var context = listener.EndGetContext(asyncResult);
listener.BeginGetContext(OnRequestArrival, this); // receive the next one
lock (requestContexts)
{
requestContexts.Enqueue(context);
}
}
It calls EndGetContext() to get something called an HttpListnerContext containing the request, and calls BeginGetContext() again to be ready for the next request.
Since there's no telling which thread this callback is called on, the requests are first stored in a Queue so that user processing is guaranteed to run on the main thread. Here I assumed that a function called ManualUpdate() is called manually every frame and processes whatever has piled up in the queue. If you don't like calling it manually, the way to go is to make DebugServer a class derived from MonoBehaviour and implement Update. I prefer to add as few gameObjects as possible, so I did it this way.
The HTTP server's interface
Next, let's look at how this DebugServer class is used.
public class DebugServer : IDisposable
{
public delegate void OnRequest(
out string outputHtml,
System.Collections.Specialized.NameValueCollection queryString,
System.IO.Stream bodyData);
public void RegisterRequestCallback(string path, OnRequest onRequest);
public static string GetLanIpAddress();
public DebugServer(int port);
public void Dispose();
public void ManualUpdate();
}
This shows just the public parts. If you want to do something like swap in a dummy implementation for the shipping product, adding an interface might be a good idea.
You construct it with a port to stand up the server, and register a callback for each URL with RegisterRequestCallback(). For example, like this.
debugServer = new DebugServer(port: 8080);
debugServer.RegisterRequestCallback("/", OnWebRequestRoot);
debugServer.RegisterRequestCallback("/api/file/upload", OnWebRequestUploadFile);
debugServer.RegisterRequestCallback("/api/file/delete", OnWebRequestDeleteFile);
debugServer.RegisterRequestCallback("/api/file/delete-all", OnWebRequestDeleteAllFile);
If the phone's address were 192.168.0.3, accessing http://192.168.0.3/ would call OnWebRequestRoot(), and accessing http://192.168.0.3/api/file/upload would call OnWebRequestUploadFile(), and so on.
The callback has the following form.
public delegate void OnRequest(
out string outputHtml,
NameValueCollection queryString,
Stream bodyData);
The interface receives the information the JavaScript side sent to the server as queryString and bodyData, and returns the HTML to send back to the browser that made the request. It's only for debugging after all, so I defined it this way to keep it as simple as possible. The arguments may grow as it gets more features.
As you can see from all this, the DebugServer layer doesn't handle concrete features such as replacing files or processing uploads. That's the job of the layer above.
Digression: out, or return value?
By the way, about this callback interface: some of you may think, "Just make the return value a string and have it return the HTML." I did it this way because in C# you can't give a return value a name.
public delegate string OnRequest(
NameValueCollection queryString,
Stream bodyData);
With this, nothing explains that the return value is HTML. Some may think you can just write a comment, but I think if you write code whose usage can't be understood without comments, you've lost.
This is a naming problem: if the name were GenerateOutputHtml() rather than OnRequest(), it would be easy to see what the return value is. But then the sense of "a function that does something when a request comes in" fades, and the emphasis shifts to generating HTML. I couldn't think of a name that felt quite right, so I decided to return it via out. I often agonize over this kind of conflict. What do you all think?
It would be nice if C# let you name return values, like Go does.
The HTML file
When accessed from a browser, it has to return HTML, and for now the assumption is that the app provides it. In this sample too, an HTML file is prepared under Assets. When the root directory is accessed, it simply returns it as is.
void OnWebRequestRoot(
out string outputHtml,
NameValueCollection queryString,
Stream bodyData)
{
outputHtml = debugServerIndexHtml;
}
An HTML file placed under Assets can be obtained as a TextAsset, so I set it on the script in the Inspector, pull the text out of it, and set it to outputHtml. If it becomes a full-fledged setup that returns different HTML depending on the URL accessed, you'll end up writing many HTML files.
The JavaScript side
We need to send the path and the file's contents to the server. This time, the path is sent as a query string, and the file's contents as the message body.
The relevant code looks like this.
var onLoad = function (arrayBuffer) {
var path = document.getElementById('path').value;
var request = new XMLHttpRequest();
request.onload = function () {
log.value = 'アップロード受理\n';
};
request.onerror = function () {
log.value = 'アップロード失敗\n';
};
request.open(
'PUT',
document.location.origin + '/api/file/upload?path=' + path,
true);
request.send(new Int8Array(arrayBuffer));
};
var onUpload = function () {
var files = document.getElementById('file').files;
if (files.length == 0) {
return;
}
var reader = new FileReader();
reader.onload = function (e) {
onLoad(e.target.result);
};
reader.readAsArrayBuffer(files[0]);
};
document.getElementById('upload').addEventListener('click', onUpload, false);
To send it, I use XmlHttpRequest. After setting up onload and onerror, you specify the URL and method with open(). The path goes in the query string, so it becomes
request.open(
'PUT',
document.location.origin + '/api/file/upload?path=' + path,
true);
That is, you append ?path=ほげほげ to the end of the URL. The address of the server (that is, the phone) can be obtained with document.location.origin.
I set the method to PUT; there seems to be a guideline that "anything that gives the same result no matter how many times it's called is PUT", so I followed it.
Finally, call send().
request.send(new Int8Array(arrayBuffer));
As the argument, you pass an ArrayBufferView such as an Int8Array.
Replacing files
Now let's look at how the server side, that is, the Unity side, accepts file uploads. This is OnWebRequestUploadFile(), which we passed to RegisterRequestCallback() earlier. It's called when a request comes to http://サーバ名/api/file/upload.
void OnWebRequestUploadFile(
out string outputHtml,
NameValueCollection queryString,
Stream bodyData)
{
outputHtml = null;
if (bodyData == null)
{
outputHtml = "中身が空.";
return;
}
var path = queryString["path"];
if (string.IsNullOrEmpty(path))
{
outputHtml = "アップロードしたファイルのパスが空.";
return;
}
DebugServerUtil.SaveOverride(path, bodyData);
loadRequested = true;
}
Look up path in queryString and you get the path. Then I save the file by calling SaveOverride() on DebugServerUtil, a handy class I prepared for saving and replacing files.
It simply writes under Application.persistentDataPath. However, in the editor I want to keep several versions of the same app at the same time, so it saves under the project folder.
public static string GetPersistentDataPath()
{
string ret;
#if UNITY_EDITOR // In the editor, directly under the project is more convenient
// Relies on GetCurrentDirectory returning the project path. If that behavior changes, this breaks!
ret = Path.Combine(Directory.GetCurrentDirectory(), "PersistentData");
#else
ret = Application.persistentDataPath;
#endif
return ret;
}
After that, reloading the files that have already been loaded reflects the change on screen. This sample reloads all three files (image, sound and json), but in practice you'd need to reload only the files that changed, and you'd probably also need to set up a mechanism to keep the code needed for reloading to a minimum.
Replacement at load time
In this sample, the processing is: "for a file loaded from StreamingAssets, if a file with the same name exists in persistentData, load that one instead".
For example, when there's StreamingAssets/image/hoge.png, if persistentDataPath/Override/image/hoge.png exists, that's loaded instead. Checking whether the file exists makes loading slower, so a proper implementation would put the list of existing files into a Dictionary at startup, but the sample doesn't do that.
Of course, for the shipping product, this feature would be disabled, and I imagine the files under StreamingAssets would be replaced with the final versions, or turned into AssetBundles and put on the game server.
If you wanted to, you could also write it so that, for AssetBundles too, whatever is placed in persistentData is loaded first in the same way. You'd no longer be able to use the standard DownloadHandlerAssetBundle, but it probably wouldn't be that much work. If it's a flow where the people doing the work make the AssetBundles on their own PCs, I think it can be made more efficient.
Problems and the future
This was just a first step; the real question is how to bring it into a product and make things more efficient. Let's look at the current problems and how it might be used in the future.
Writing HTML and JavaScript is a pain
The biggest pain this time was writing the HTML and JavaScript. I normally live in C#, so switching my head to another language has a cost. And someone with no JavaScript experience wouldn't even think of trying.
So ideally, you write code in C# and the HTML and JavaScript are generated. You'd specify UI elements such as a file selection input for uploading, a message log, text boxes, sliders and buttons in C#, and generate HTML from them. It's only for development, so looks can be ignored, and as long as you don't build features like layout specification, I don't think it would be that much work.
In practice, you don't put things in StreamingAssets
In a game of any real size, you need to cut the size of the app itself as much as possible, so you'd rarely put things in StreamingAssets. They'd be downloaded from the server on first run.
In that case, "replace things that were originally in StreamingAssets when loading them" isn't very useful. It would be good to extend it so the same replacement works for things downloaded from the server too.
It only works for things not put in AssetBundles
Unity games usually put data in AssetBundles. But if the artists and game designers who make the data don't normally work in Unity, they can't build AssetBundles locally. If they can't do it locally, "transfer directly from your local PC to the phone" loses its point.
Then it would need to be a mechanism where "things that were originally in AssetBundles can also be replaced". For example, to replace image.png inside hoge.unity3d, you'd specify the upload path as "hoge.unity3d/image.png". If a file exists at this path, it is used instead of the asset in the AssetBundle.
But implementing that is quite a pain. I don't even know if it's possible. I haven't even thought yet about how to do something like swapping just the Texture that a Sprite in an AssetBundle depends on.
In that case, another option is "not putting things into AssetBundles that don't need to be there in the first place". If you accept not compressing textures, images can be turned into textures directly from png or jpeg, so you can load them even if you put them in your own zip.
For example, if you make effects with Spine, what Spine outputs is png textures and a proprietary binary containing the animation information. If you made a plugin for Spine that packs these into a zip and uploads it, you could get to a state where "save in Spine and it's instantly reflected in the game on the phone", even on a machine without Unity.
Of course, if your culture is that artists and game designers use the UnityEditor, there's no such problem, and you can simply build the AssetBundle and send it. That's probably how Unity is meant to be used. I do feel our company, where almost only programmers use the UnityEditor, is unusual (though recently more artists use it too). Even in that case, though, you need to put tools in place, such as building an AssetBundle and sending it to the device with one button. Cutting even a single extra click matters, both for raising mass-production efficiency and for reducing the support workload.
Implementing reload is surprisingly tricky
Implementing reload turns out to be surprisingly tricky. If you want every asset to be reloadable the moment it's uploaded, you'd need a unified mechanism that saves you from writing it case by case.
For an image, for example, it ends up set on a UI.Image or a Material and displayed, so you have to identify which Image or Material the newly uploaded image is plugged into and go swap it. I think it would be good to be able to do something like this: make some lovely base class, and as long as character art, background images and item images are swapped using classes derived from that lovely base class, replacement in response to uploads just happens. How exactly to do that is something I still need to work out.
What to do about parameter tuning being in Google Sheets
In our company's flow, things like item data, help text and enemy data are set and tuned on Google Sheets. The data isn't on the local PC to begin with, so this technique can't help at all.
If it were done in Excel locally, you could output a csv, transfer it directly to the phone and replace it, but none of our products use that kind of flow, so it can't help there either.
When making something like a small puzzle game, I think a flow of turning placement data and parameters into json per stage, and editing and trying them, would be good, but I don't know whether it fits so-called social games. That's something I'd like to talk about with game designers going forward.
For small puzzle games and the like, it would be good to make a stage editor that runs in the browser and put it on top of this mechanism. I think there are many situations where JavaScript skills would come in handy.
Compromises
With this many tricky issues, I think realistic use, at least in the near term, will look something like this.
- For file replacement, settle for "it's replaced once you go through a scene transition that reloads".
- For example, it's replaced if you go back to the title screen and go to that screen again.
- In many places, going back to the previous screen will probably be enough.
- Tuning game parameters with sliders and text boxes is easy.
- As long as you write the HTML and JavaScript, you can build UI in the browser that lets you tune, for example, an effect's playback speed or offset, or the strength of enemies in the game. There are few technical problems.
- Even simply viewing information is effective.
- Logs shown on the device get in the way of the game, but it's nice to send the logs to the browser and see them on a big screen. Even better if you can save them.
- Showing FPS, memory, the number of game objects, the game's progress and so on in the browser is quite handy.
- If you want to avoid polling, WebSocket? ServerSentEvent?
- There's also the idea of showing the hierarchy and inspector in the browser and editing them
Closing
There are still many problems, but I think this technique, which connects the PC and the actual phone directly and extends the phone's small screen into the browser, has all kinds of uses.
I look forward to your ideas!