Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. Dismiss Notice

Mobile WebSocket [Unity Free Android/iOS]

Discussion in 'Assets and Asset Store' started by talklittle, Jul 11, 2013.

  1. talklittle

    talklittle

    Joined:
    Aug 17, 2012
    Posts:
    16
    Hey guys I'm happy to announce the availability of Mobile WebSocket native plugin for Android and iOS. It lets you create WebSocket client communication on those platforms.

    It's optimized specifically for mobile, with adjustable memory constraints and a minimal amount of managed-to-unmanaged function calls.

    Note that you'll have to run it on an actual Android/iOS device. The plugin does nothing in the Unity Editor and desktop platforms.

    Also note that it does not require Unity Pro, since it is not using .NET sockets. I don't have Unity Pro yet, which is why I created this plugin. Hope it's useful for you too.

    Here's the link: http://u3d.as/51U

    Please post feedback/questions in this thread. Thanks!


    EDIT: I forgot to post some sample code! I designed it with the goal of a dead-simple API. Here's the sample test script included in the package:

    Code (csharp):
    1. #pragma strict
    2.  
    3. public var testGUIText:UnityEngine.GUIText;
    4.  
    5. private var webSocket:MobileWebSocket;
    6. private var numClicks = 0;
    7.  
    8.  
    9. function Start() {
    10.     webSocket = gameObject.GetComponent(MobileWebSocket);
    11. }
    12.  
    13. function OnGUI() {
    14.     if (GUI.Button (Rect (10,10,150,100), "Send Hello")) {
    15.         if (webSocket.IsOpen) {
    16.             webSocket.SendTextMessage("Hello WebSocket " + (++numClicks));
    17.         }
    18.     }
    19. }
    20.  
    21. function Update() {
    22.     if (webSocket.HasIncomingMessages) {
    23.         var messages:Array = webSocket.TakeMessages();
    24.         var length:int = messages.length;
    25.         for (var i:int = 0; i < length; i++) {
    26.             var message = messages[i];
    27.             if (message instanceof byte[]) {
    28.                 var binary:byte[] = message as byte[];
    29.                 Debug.Log("New binary message of length " + binary.Length);
    30.             }
    31.             else if (message instanceof String) {
    32.                 var text:String = message as String;
    33.                 testGUIText.text = text + "\n" + testGUIText.text;
    34.             }
    35.         }
    36.     }
    37. }
     
    Last edited: Jul 11, 2013
    LogicFlow likes this.
  2. gfxguru

    gfxguru

    Joined:
    Jun 5, 2010
    Posts:
    107
    Good to hear that socket is possible in free version of unity. But the asset store details says that
    Requires Unity 4.1.5 or higher.

    Can we make it work for 3.5.7??
     
  3. talklittle

    talklittle

    Joined:
    Aug 17, 2012
    Posts:
    16
    Hey gfxguru thanks for the question. My guess is probably could get it working in 3.5.7, I haven't tried yet.

    EDIT: Ignore the below. Asset Bundles are entirely unrelated to Asset Store. http://docs.unity3d.com/Documentation/Manual/AssetBundlesIntro.html

    Before I try that though, let me point out the new changelog of Unity 4.2 which indicates that "Asset bundles built in prior versions of Unity are no longer compatible with Unity 4.2 (this has been necessary because of changes to how built-in resources are handled)." I hope this doesn't mean I have to choose between 4.2 and prior versions!

    For now let me try redoing the plugin for 3.5.7. If I have to worry about 4.2 separately, maybe the Asset Store will accept a separate package. I should do some more research about that.
     
    Last edited: Jul 23, 2013
  4. talklittle

    talklittle

    Joined:
    Aug 17, 2012
    Posts:
    16
    Good news, I repackaged in Unity 3.5.7 and it works fine in my tests on Android and iOS. Hopefully will be accepted into the Asset Store for Unity 3.5.7 and above!
     
  5. gfxguru

    gfxguru

    Joined:
    Jun 5, 2010
    Posts:
    107
    can this be used to communicate with socket.io servers?
     
  6. talklittle

    talklittle

    Joined:
    Aug 17, 2012
    Posts:
    16
    It does not work with Socket.IO directly (for now), since Socket.IO uses some additional handshake protocols on top of WebSocket.

    It does work with WebSocket.IO, made by the same people as Socket.IO and with a similar API to Socket.IO: https://github.com/LearnBoost/websocket.io

    Example server for WebSocket.IO, which I just tested with MobileWebSocket Unity client:

    Code (csharp):
    1. var ws = require('websocket.io')
    2.   , server = ws.listen(8080)
    3.  
    4. server.on('connection', function (socket) {
    5.   socket.on('message', function(text) {
    6.     socket.send('echo: ' + text);
    7.   });
    8.   socket.on('close', function () { });
    9. });
    10.  
     
  7. talklittle

    talklittle

    Joined:
    Aug 17, 2012
    Posts:
    16
    Version 1.0.2 released. Now works with Unity 3.5.7.
     
  8. sean.w.k

    sean.w.k

    Joined:
    Jul 19, 2013
    Posts:
    2
    Would it be possible to support Android 2.2 ( API level 8 )? Thanks.
     
  9. talklittle

    talklittle

    Joined:
    Aug 17, 2012
    Posts:
    16
    Hi there, thanks for the question.

    I've submitted a new version 1.0.3 which supports Android 2.2 (API Level 8), with one major caveat:

    Secure WebSockets (wss://) are not supported on Android 2.2 due to an Android framework bug with SSL handshake: https://code.google.com/p/android/issues/detail?id=12955

    Regular ws:// works fine though.

    Therefore, it is still recommended to use minimum Android 2.3.3 (API Level 10). I've indicated this in the README.txt for version 1.0.3.
     
    Last edited: Jul 31, 2013
  10. sean.w.k

    sean.w.k

    Joined:
    Jul 19, 2013
    Posts:
    2
    Thanks for the answer!
     
  11. Ryuuguu

    Ryuuguu

    Joined:
    Apr 14, 2007
    Posts:
    387
    I am trying to call this with cs code. I first am trying to just port your sample code but it crashes every time.
    Code (csharp):
    1.  
    2.     void  Update() {
    3.         if (webSocket.HasIncomingMessages) {
    4.             var messages = webSocket.TakeMessages();
    5.             for (int i = 0; i < messages.Length; i++) {
    6.                 var message = messages[i]; //crash
    7.                 if (message.GetType () == typeof(string)) {   //or crash
    8.                     string text = message as string;
    9.                     testGUIText.text = text + "\n" + testGUIText.text;
    10.                 }
    11.             }
    12.         }
    13.     }
    14.  
    it crashes either at the var message = messages; or the next line I think. Do have a working sample in cs?

    Cheers Grant
     
  12. talklittle

    talklittle

    Joined:
    Aug 17, 2012
    Posts:
    16
    Hi Ryuuguu, here's the sample in C#:

    Code (csharp):
    1. using UnityEngine;
    2. using System.Collections;
    3.  
    4. public class CSTestMobileWebSocket : MonoBehaviour {
    5.  
    6.     public GUIText testGUIText;
    7.  
    8.     private MobileWebSocket webSocket;
    9.     private int numClicks = 0;
    10.  
    11.     // Use this for initialization
    12.     void Start () {
    13.         this.webSocket = GetComponent<MobileWebSocket>();
    14.     }
    15.    
    16.     // Update is called once per frame
    17.     void Update () {
    18.         if (webSocket.HasIncomingMessages) {
    19.             var messages = webSocket.TakeMessages();
    20.             int length = messages.Length;
    21.             for (int i = 0; i < length; i++) {
    22.                 var message = messages[i];
    23.                 if (message is byte[]) {
    24.                     byte[] binary = message as byte[];
    25.                     Debug.Log("New binary message of length " + binary.Length);
    26.                 }
    27.                 else if (message is string) {
    28.                     string text = message as string;
    29.                     testGUIText.text = text + "\n" + testGUIText.text;
    30.                 }
    31.             }
    32.         }
    33.     }
    34.    
    35.     void OnGUI() {
    36.         if (GUI.Button (new Rect (10,10,150,100), "Send Hello")) {
    37.             if (webSocket.IsOpen) {
    38.                 webSocket.SendTextMessage("CS Hello WebSocket " + (++numClicks));
    39.             }
    40.         }
    41.     }
    42. }
     
  13. Ryuuguu

    Ryuuguu

    Joined:
    Apr 14, 2007
    Posts:
    387
    Thanks, I found my problem. I used

    Code (csharp):
    1. if (message.GetType () == typeof(string))
    and you use

    Code (csharp):
    1. if (message is string)
    Mine crashes at

    Code (csharp):
    1. string text = message as string;
    Although I don't understand why.

    Cheers,
    Grant
     
  14. talklittle

    talklittle

    Joined:
    Aug 17, 2012
    Posts:
    16
    So you are still getting crashes? Which device are you testing on, including OS version number? Are you using the exact sample script I posted?
     
  15. Ryuuguu

    Ryuuguu

    Joined:
    Apr 14, 2007
    Posts:
    387
    Sorry I was not clear. I do not have crashes now. if I "message is string" all is fine. I just do not understand why "message.GetType () == typeof(string)" did not work. Unless maybe message is a subclass of string.

    So MobileWeb sockets is working fine for me.
     
    LogicFlow likes this.
  16. Ohms

    Ohms

    Joined:
    May 3, 2009
    Posts:
    36
    I've bought this asset. It works fine !! Thanks for this development.

    Did you planned a Windows Phone 8 and Windows RT release for MobileWebSocket ?
     
    LogicFlow likes this.
  17. Murax

    Murax

    Joined:
    Sep 19, 2013
    Posts:
    1
    I dont want to start immediately, Need to start after url set. How to do that?

    I tried with enabling once WebSocketUrl done. But even socket is open, sendingMessage not received on other end.
     
    Last edited: Feb 27, 2014
  18. talklittle

    talklittle

    Joined:
    Aug 17, 2012
    Posts:
    16
    Hi Murax, this is the intended way to do it, by setting webSocket.enabled = true; when you are ready. ConnectOnStart=false is not useful in most situations.

    Can you show some code that you are using to send the messages? Thanks.
     
    Last edited: Feb 27, 2014
  19. dioh76

    dioh76

    Joined:
    Mar 1, 2014
    Posts:
    1
    Hi,
    I purchased your mobile websocket in asset store a few minute ago. But I can't download asset like this
    $??? 098.png

    So I want to get your asset by email. Is it possible?

    My email address is dongil.oh@gmail.com

    My Invoice Information is below
    Invoice No. 301433507

    Date 01-Mar-2014
    Due Date 01-Mar-2014
    Customer No. 3092488
    Order No. OR301433507
    PO No. 4335294

    I expect to get your feedback as soon as possible.

    thanks
     
  20. talklittle

    talklittle

    Joined:
    Aug 17, 2012
    Posts:
    16
    Hello, please contact Unity Asset Store support, since it is a problem with Unity. I only distribute the plugin via the asset store. Sorry.
     
  21. DaehoChoi

    DaehoChoi

    Joined:
    Mar 5, 2014
    Posts:
    3
    hi~ i'm using this plugin in my game.
    i think this is very good plugin.
    i have a question.
    i wonder how i can disconnect and reconnect websocket in my game manually.
    and i also wonder how i can set URL manually.
     
    Last edited: Mar 5, 2014
  22. talklittle

    talklittle

    Joined:
    Aug 17, 2012
    Posts:
    16
    Hi Daeho, your WebSocketManager object will be in your scene. Using that, you can use the function webSocketManager.GetComponent(WebSocket) in JavaScript or GetComponent<WebSocket>() in C# to get the WebSocket script object.

    To connect/disconnect, use webSocket.enabled = true; or webSocket.enabled = false;

    To change URL, use webSocket.WebSocketUri = "wss://echo.websocket.org"
     
  23. Geng

    Geng

    Joined:
    Apr 29, 2014
    Posts:
    1
    Hi TalkLittle, I have some devices which lose wifi and the websocket is disconnected frequently and needs to be reconnected in the code. Do you have a built in method for this?

    Could you explain how to attempt to create a new client websocket again with your library? Thanks
     
  24. talklittle

    talklittle

    Joined:
    Aug 17, 2012
    Posts:
    16
    Hi Geng, one way you could do it is: mobileWebSocket.enabled = false; mobileWebSocket.enabled = true;

    When you disable the mobileWebSocket it will disconnect. When you enable it will reconnect.

    Unfortunately there is no built-in way to detect wifi disconnections. One way to do it would be to reset a timer every time you receive a message (and on the server side, consider sending a heartbeat packet). If no data is received after, say, 5 seconds, the timer fires and reconnects the socket on the Unity client side.
     
  25. JamesAMG

    JamesAMG

    Joined:
    Dec 4, 2013
    Posts:
    1
    Any chance of some kind of demo? After being continually burned by unity3d plugins, $75 is a big ask.
     
  26. BoinMaster

    BoinMaster

    Joined:
    Jul 22, 2014
    Posts:
    3
    Hi TalkLittle, My app succeeded creating socket communication with MobileWebSocket asset.
    But suddenly, it can't pass call back function from native to C# on both iOS and Android devices.
    *The function is public void SetHasIncomingMessages(string booleanString)function on MobileWebSocket.cs.
    I can confirm logs that devices receive messages from server, but the app itself can't receive messages.

    The logs are below.
    07-10 12:29:05.984 D/de.tavendo.autobahn.WebSocketWriter( 6049): WRITTEN (WS): 1308
    07-10 12:29:06.023 D/de.tavendo.autobahn.WebSocketReader( 6049): READ (WS): 1
    07-10 12:29:06.023 D/de.tavendo.autobahn.WebSocketReader( 6049): READ (WS): 1307
    07-10 12:29:06.023 I/e ( 6049): Discarding oldest payload

    I think the app deletes receiving data fom the oldest, but if you know how to detect that actually app deletes data, I would like to know the way to do that.
    Also if you ever saw problems like this, I really appreciate your help.
     
    Last edited: Jul 24, 2014
  27. talklittle

    talklittle

    Joined:
    Aug 17, 2012
    Posts:
    16
    Hi BoinMaster, the intended usage of the library is to take the messages -- using the TakeMessages() function -- immediately upon receiving them. If you need to keep the messages for a long time, add them to your own data structure that you created separately.

    The message queue buffer is of fixed length, and the oldest messages will be deleted when the buffer is full. So make sure to check for HasIncomingMessages, and take the messages as soon as you can, in your Update() function. (Refer to initial post for example of intended usage.)
     
  28. BoinMaster

    BoinMaster

    Joined:
    Jul 22, 2014
    Posts:
    3
    Thanks TalkLittle! I appreciate your quick response!
    I already wrote message receiving process according to sample codes, and it's below.

    void Update () {
    if (webSocket.HasIncomingMessages) {
    var messages = webSocket.TakeMessages();
    }
    }

    It normally works without problems.
    But suddenly, public void SetHasIncomingMessages(string booleanString) function on MobileWebSocket.cs (that's supposed to be called from native) now isn't called.
    So webSocket.HasIncomingMessages doesn't become true. This is what I think the problem is.

    Possibly, do you think this below could happen?
    There are some problems at native code processes of MobileWebSocket,
    and public void SetHasIncomingMessages(string booleanString) on MobileWebSocket.cs isn't called.
     
  29. talklittle

    talklittle

    Joined:
    Aug 17, 2012
    Posts:
    16
    Thank you for that info BoinMaster. A bug is certainly possible.

    Can you please provide more details about when the problem occurs? Is it after a specific number of messages? Are you using wss:// (secure websockets)? Do you have an example WebSocket message that fails, and a test server I can test against?

    Sounds like it is only Android giving you trouble so far, so we can start debugging there.
     
  30. cms

    cms

    Joined:
    Sep 19, 2011
    Posts:
    43
    Hello,
    We are trying to implement a one-to-one chat. We have done this in our server (php+mySql) with the mobile of both persons in the chat "checking" the server every 10 seconds.. (probably a crappy solution).

    I found in the internet that web sockets could be the fastest way to send/receive messages to the other users.

    We would be happy to buy the plugin, if that works for our chat.. could you tell us if that could be a solution ?

    And if so, we do not know how to implement "web sockets" in the server side. Can anybody give us some hints (sample code, urls, etc) ?

    THANK YOU
     
  31. talklittle

    talklittle

    Joined:
    Aug 17, 2012
    Posts:
    16
    Hi, web sockets are indeed faster than polling. However for a chat app, I'd recommend something like Push Notifications instead of Web Sockets. Web Sockets are overkill for sending simple chat messages back and forth. Web Sockets in games are good for sending dynamic data of different types, when data is constantly flowing. The problem with using it in a chat application, is you're keeping a constant connection open to the server, wasting the users' data plans and battery.

    Push Notifications are powerful in a different way, and integrated better with mobile operating systems, allowing you to do cooler things like notifying users about chat messages even when the app is in the background.

    So thanks for considering this websockets plugin, but I'd recommend looking into Push Notifications and see if that is a better fit for you.
     
  32. Shin_S

    Shin_S

    Joined:
    Jan 22, 2015
    Posts:
    14
    Hi!
    I'm new to Unity and I'd like to know how painful will it be to adapt this plugin to work on windows phone too please?
    My game needs to works on iOS/Android and WP so I'll looking forward a solution which includes all these platforms.
    Thx! And really great work by the way :)
     
    Last edited: Jan 22, 2015
  33. talklittle

    talklittle

    Joined:
    Aug 17, 2012
    Posts:
    16
    Thanks for your interest. Unfortunately this plugin does not support Windows Phone. You'll have to seek an alternate solution.
     
  34. Shin_S

    Shin_S

    Joined:
    Jan 22, 2015
    Posts:
    14
    Thank you for your answer! You do not have a free "trial" version?
    It seems that there is no plugin in the asset store that handles this, poor windows phones ^^
    If somebody knows one feel free to send me a link ;)
     
  35. Arkade

    Arkade

    Joined:
    Oct 11, 2012
    Posts:
    653
    More question than answer - would Best HTTP with Good ol' Sockets work?