• Products
  • Solutions
  • Made with Unity
  • Learning
  • Support & Services
  • Community
  • Asset Store
  • Get Unity

UNITY ACCOUNT

You need a Unity Account to shop in the Online and Asset Stores, participate in the Unity Community and manage your license portfolio. Login Create account
  • Blog
  • Forums
  • Answers
  • Evangelists
  • User Groups
  • Beta Program
  • Advisory Panel

Navigation

  • Home
  • Products
  • Solutions
  • Made with Unity
  • Learning
  • Support & Services
  • Community
    • Blog
    • Forums
    • Answers
    • Evangelists
    • User Groups
    • Beta Program
    • Advisory Panel

Unity account

You need a Unity Account to shop in the Online and Asset Stores, participate in the Unity Community and manage your license portfolio. Login Create account

Language

  • Chinese
  • Spanish
  • Japanese
  • Korean
  • Portuguese
  • Ask a question
  • Spaces
    • Default
    • Help Room
    • META
    • Moderators
    • Topics
    • Questions
    • Users
    • Badges
  • Home /
avatar image
0
Question by MCLD3D · Sep 19, 2016 at 06:14 PM · serverstreamingassetshttpportlocalhost

Create a simple http server on the streaming asset folder for access it via http://localhost:*port*/ on Browser

Hello, I would like to create a local http server on my streaming asset when the Unity App launch, for open local web site on a browser (not from the uniy app)

Example : I launch my app on PC or MAC,

I open a browser and go to http://localhost:1234/ it open the local web site in the streaming asset of my Unity App. The local web site only uses javascript, images, css, and html files

if I close the unity app, the server is closed

any hints or ideas?

Thanks

Comment
Add comment
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users

2 Replies

· Add your reply
  • Sort: 
avatar image
1
Best Answer

Answer by MCLD3D · Sep 21, 2016 at 07:10 PM

I found a solution :

 using UnityEngine;
 using System.Collections;
 using System;
 using System.Collections.Generic;
 using System.Linq;
 using System.Text;
 using System.Net.Sockets;
 using System.Net;
 using System.IO;
 using System.Threading;
 using System.Diagnostics;
 
 public class SimpleHTTPServerComponent : MonoBehaviour
 {
         SimpleHTTPServer myServer;
         public string FirstIndexPath = "";
 
         public void StartServer()
         {
                 myServer = new SimpleHTTPServer(Path.Combine(Application.streamingAssetsPath, "App"));
                 Application.OpenURL("http:/localhost:" + myServer.Port + "/" + FirstIndexPath);
         }
 
         public void StopServer()
         {
                 Application.Quit();
         }
 
         void OnApplicationQuit()
         {
                 myServer.Stop();
         }
 
 
         class SimpleHTTPServer
         {
                 private readonly string[] _indexFiles =
                         { 
                                 "index.html", 
                                 "index.htm", 
                                 "default.html", 
                                 "default.htm" 
                         };
 
                 private static IDictionary<string, string> _mimeTypeMappings = new Dictionary<string, string>(StringComparer.InvariantCultureIgnoreCase)
                 {
                 #region extension to MIME type list
                         { ".asf", "video/x-ms-asf" },
                         { ".asx", "video/x-ms-asf" },
                         { ".avi", "video/x-msvideo" },
                         { ".bin", "application/octet-stream" },
                         { ".cco", "application/x-cocoa" },
                         { ".crt", "application/x-x509-ca-cert" },
                         { ".css", "text/css" },
                         { ".deb", "application/octet-stream" },
                         { ".der", "application/x-x509-ca-cert" },
                         { ".dll", "application/octet-stream" },
                         { ".dmg", "application/octet-stream" },
                         { ".ear", "application/java-archive" },
                         { ".eot", "application/octet-stream" },
                         { ".exe", "application/octet-stream" },
                         { ".flv", "video/x-flv" },
                         { ".gif", "image/gif" },
                         { ".hqx", "application/mac-binhex40" },
                         { ".htc", "text/x-component" },
                         { ".htm", "text/html" },
                         { ".html", "text/html" },
                         { ".ico", "image/x-icon" },
                         { ".img", "application/octet-stream" },
                         { ".svg", "image/svg+xml" },
                         { ".iso", "application/octet-stream" },
                         { ".jar", "application/java-archive" },
                         { ".jardiff", "application/x-java-archive-diff" },
                         { ".jng", "image/x-jng" },
                         { ".jnlp", "application/x-java-jnlp-file" },
                         { ".jpeg", "image/jpeg" },
                         { ".jpg", "image/jpeg" },
                         { ".js", "application/x-javascript" },
                         { ".mml", "text/mathml" },
                         { ".mng", "video/x-mng" },
                         { ".mov", "video/quicktime" },
                         { ".mp3", "audio/mpeg" },
                         { ".mpeg", "video/mpeg" },
                         { ".mp4", "video/mp4" },
                         { ".mpg", "video/mpeg" },
                         { ".msi", "application/octet-stream" },
                         { ".msm", "application/octet-stream" },
                         { ".msp", "application/octet-stream" },
                         { ".pdb", "application/x-pilot" },
                         { ".pdf", "application/pdf" },
                         { ".pem", "application/x-x509-ca-cert" },
                         { ".pl", "application/x-perl" },
                         { ".pm", "application/x-perl" },
                         { ".png", "image/png" },
                         { ".prc", "application/x-pilot" },
                         { ".ra", "audio/x-realaudio" },
                         { ".rar", "application/x-rar-compressed" },
                         { ".rpm", "application/x-redhat-package-manager" },
                         { ".rss", "text/xml" },
                         { ".run", "application/x-makeself" },
                         { ".sea", "application/x-sea" },
                         { ".shtml", "text/html" },
                         { ".sit", "application/x-stuffit" },
                         { ".swf", "application/x-shockwave-flash" },
                         { ".tcl", "application/x-tcl" },
                         { ".tk", "application/x-tcl" },
                         { ".txt", "text/plain" },
                         { ".war", "application/java-archive" },
                         { ".wbmp", "image/vnd.wap.wbmp" },
                         { ".wmv", "video/x-ms-wmv" },
                         { ".xml", "text/xml" },
                         { ".xpi", "application/x-xpinstall" },
                         { ".zip", "application/zip" },
                 #endregion
                 };
                 private Thread _serverThread;
                 private string _rootDirectory;
                 private HttpListener _listener;
                 private int _port;
 
                 public int Port
                 {
                         get { return _port; }
                         private set { }
                 }
 
                 /// <summary>
                 /// Construct server with given port.
                 /// </summary>
                 /// <param name="path">Directory path to serve.</param>
                 /// <param name="port">Port of the server.</param>
                 public SimpleHTTPServer(string path, int port)
                 {
                         this.Initialize(path, port);
                 }
 
                 /// <summary>
                 /// Construct server with suitable port.
                 /// </summary>
                 /// <param name="path">Directory path to serve.</param>
                 public SimpleHTTPServer(string path)
                 {
                         //get an empty port
                         TcpListener l = new TcpListener(IPAddress.Loopback, 0);
                         l.Start();
                         int port = ((IPEndPoint)l.LocalEndpoint).Port;
                         l.Stop();
                         this.Initialize(path, port);
                 }
 
                 /// <summary>
                 /// Stop server and dispose all functions.
                 /// </summary>
                 public void Stop()
                 {
                         _serverThread.Abort();
                         _listener.Stop();
                 }
 
                 private void Listen()
                 {
                         _listener = new HttpListener();
                         _listener.Prefixes.Add("http://*:" + _port.ToString() + "/");
                         _listener.Start();
                         while (true)
                         {
                                 try
                                 {
                                         HttpListenerContext context = _listener.GetContext();
                                         Process(context);
                                 } catch (Exception ex)
                                 {
                                         print(ex);
                                 }
                         }
                 }
 
                 private void Process(HttpListenerContext context)
                 {
                         string filename = context.Request.Url.AbsolutePath;
                         print(filename);
                         filename = filename.Substring(1);
 
                         if (string.IsNullOrEmpty(filename))
                         {
                                 foreach (string indexFile in _indexFiles)
                                 {
                                         if (File.Exists(Path.Combine(_rootDirectory, indexFile)))
                                         {
                                                 filename = indexFile;
                                                 break;
                                         }
                                 }
                         }
 
                         filename = Path.Combine(_rootDirectory, filename);
 
                         if (File.Exists(filename))
                         {
                                 try
                                 {
                                         context.Response.StatusCode = (int)HttpStatusCode.OK;
                                         Stream input = new FileStream(filename, FileMode.Open);
 
                                         //Adding permanent http response headers
                                         string mime;
                                         context.Response.ContentType = _mimeTypeMappings.TryGetValue(Path.GetExtension(filename), out mime) ? mime : "application/octet-stream";
                                         context.Response.ContentLength64 = input.Length;
                                         context.Response.AddHeader("Date", DateTime.Now.ToString("r"));
                                         context.Response.AddHeader("Last-Modified", System.IO.File.GetLastWriteTime(filename).ToString("r"));
 
                                         byte[] buffer = new byte[1024 * 16];
                                         int nbytes;
                                         while ((nbytes = input.Read(buffer, 0, buffer.Length)) > 0)
                                                 context.Response.OutputStream.Write(buffer, 0, nbytes);
                                         input.Close();
 
 
                                         context.Response.OutputStream.Flush();
                                 } catch (Exception ex)
                                 {
                                         context.Response.StatusCode = (int)HttpStatusCode.InternalServerError;
                                         print(ex);
                                 }
 
                         } else
                         {
                                 context.Response.StatusCode = (int)HttpStatusCode.NotFound;
                         }
 
                         context.Response.OutputStream.Close();
                 }
 
                 private void Initialize(string path, int port)
                 {
                         this._rootDirectory = path;
                         this._port = port;
                         _serverThread = new Thread(this.Listen);
                         _serverThread.Start();
                 }
 
 
         }
 }
Comment
Add comment · Show 2 · Share
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users
avatar image kartoonist435 · Mar 11 at 07:30 PM 0
Share

I can't get this to work on an android tablet. I only get that the localhost can't be found. I've tried streamingAssetsPath and folders local on the android with no success. Any ideas would be great.

avatar image AccentDave · Nov 12 at 05:41 PM 0
Share

Will this work on Android? I need to have my Android-based app serve a web page to another device on the same LAN

avatar image
0

Answer by Sirpion · Sep 16, 2017 at 10:34 AM

Here is an big example of a simple http server: https://www.assetstore.unity3d.com/en/#!/content/84138

With the source code of the frontend (Angular 2)

Comment
Add comment · Show 1 · Share
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users
avatar image AccentDave · Nov 12 at 05:50 PM 0
Share

Does that work on Android?

Your answer

Hint: You can notify a user about this post by typing @username

Up to 2 attachments (including images) can be used with a maximum of 524.3 kB each and 1.0 MB total.

Welcome to Unity Answers

The best place to ask and answer questions about development with Unity.

To help users navigate the site we have posted a site navigation guide.

If you are a new user to Unity Answers, check out our FAQ for more information.

Make sure to check out our Knowledge Base for commonly asked Unity questions.

If you are a moderator, see our Moderator Guidelines page.

We are making improvements to UA, see the list of changes.



Follow this Question

Answers Answers and Comments

6 People are following this question.

avatar image avatar image avatar image avatar image avatar image avatar image

Related Questions

how to Post link ( Ruby Script) through unity3d ? 1 Answer

Failed to connect to localhost port 80: Connection refused 2 Answers

Best cross platform Http Library? 1 Answer

How do I send data to a cloud server like Amazon EC2? 1 Answer

List of HTTP User-Agent's in Unity for various platforms? 1 Answer

  • Anonymous
  • Sign in
  • Create
  • Ask a question
  • Spaces
  • Default
  • Help Room
  • META
  • Moderators
  • Explore
  • Topics
  • Questions
  • Users
  • Badges