x


Unity async socket connection

Hi everyone, so I have a problem after connecting to an arduino with a wifly module via sockets in Unity. I have this code attached to my main camera:

    using UnityEngine;
    using System.Collections;
    using System;
    using System.Threading;
    using System.Text;
    using System.Net;
    using System.Net.Sockets;

    public class wifly : MonoBehaviour
    {
        public static int i = 0;
        public static string message;
        public static string myVal;

        // Use this for initialization
        void Start()
        {
            int workerThreads, completionThreads;
            ThreadPool.GetAvailableThreads(out workerThreads, out completionThreads);
            Debug.Log("Worker: " + workerThreads + " Completion: " + completionThreads);
            Debug.Log("Setting IP address");
            IPAddress ipAddress = IPAddress.Parse("169.254.1.21");
            IPEndPoint ipEndpoint = new IPEndPoint(ipAddress, 2000);

            Debug.Log("Creating socket");
            Socket clientSocket = new Socket(
             AddressFamily.InterNetwork,
             SocketType.Stream,
             ProtocolType.Tcp);

            //Asynchronous call
            Debug.Log("Beginning Asynchronous call");
            IAsyncResult asyncConnect = clientSocket.BeginConnect(
             ipEndpoint,
             new AsyncCallback(connectCallback),
             clientSocket);
            Console.Write("Connection in progress.");
            if (writeDot(asyncConnect) == true)
            {
                // allow time for callbacks to
                // finish before the program ends
                Thread.Sleep(3000);
            }
        }

        // used to pass state information to delegate
        class StateObject
        {
            internal byte[] sBuffer;
            internal Socket sSocket;
            internal StateObject(int size, Socket sock)
            {
                sBuffer = new byte[size];
                sSocket = sock;
            }
        }

        public static void connectCallback(IAsyncResult asyncConnect)
        {
            Debug.Log("Beginning connectCallback");
            Socket clientSocket = (Socket)asyncConnect.AsyncState;
            clientSocket.EndConnect(asyncConnect);
            Debug.Log("Operation Completed");
            // arriving here means the operation completed
            // (asyncConnect.IsCompleted = true) but not
            // necessarily successfully
            if (clientSocket.Connected == false)
            {
                Debug.Log(".client is not connected.");
                return;
            }
            else Debug.Log(".client is connected.");
            StateObject stateObject = new StateObject(1, clientSocket);
            // this call passes the StateObject because it
            // needs to pass the buffer as well as the socket
            while(true)
            {
                IAsyncResult asyncReceive =
                 clientSocket.BeginReceive(
                 stateObject.sBuffer,
                 0,
                 stateObject.sBuffer.Length,
                 SocketFlags.None,
                 new AsyncCallback(receiveCallback),
                 stateObject);
                writeDot(asyncReceive);
            }
        }

        public static void receiveCallback(IAsyncResult asyncReceive)
        {
            StateObject stateObject = (StateObject)asyncReceive.AsyncState;
            //int bytesReceived = stateObject.sSocket.EndReceive(asyncReceive);
            string message = Encoding.ASCII.GetString(stateObject.sBuffer);
            print(" Message: " + message);
            if(i==2)
            {
                stateObject.sSocket.Shutdown(SocketShutdown.Both);
                stateObject.sSocket.Close();
            }
        }
        // times out after 2 seconds but operation continues
        internal static bool writeDot(IAsyncResult ar)
        {
            int i = 0;
            while (ar.IsCompleted == false)
            {
                if (i++ > 20)
                {
                    print("Timed out.");
                    return false;
                }
                print(".");
                Thread.Sleep(100);
            }
            return true;
        }

        void OnGUI()
        {
            if(GUI.Button (new Rect(120,10,100,20), "disconnect"))
            {
                i = 2;
            }
        }
    }

Everything works fine but one thing, you can see this line there

"string message = Encoding.ASCII.GetString(stateObject.sBuffer);"

it outputs the message received from the arduino, the problem is that I cannot store this value anywhere except just writing it to the console, I tried storing it in variables in many ways, but all those variables showed me was "Null" as their value. I figure this issue has to do something with these processes working on different threads, is there a way I could use those values outside the thread, or maybe store them somewhere else somehow?

Thanks ;)

more ▼

asked Jan 19 '12 at 03:13 AM

LastTemplar gravatar image

LastTemplar
76 9 12 15

anyone? please?

Jan 19 '12 at 11:35 AM LastTemplar
(comments are locked)
10|3000 characters needed characters left

1 answer: sort voted first

I don't know if this would help but Unity probably doesn't play well with ThreadPool.

more ▼

answered Jun 16 '12 at 06:36 PM

mcroswell gravatar image

mcroswell
245 4 4 13

(comments are locked)
10|3000 characters needed characters left
Your answer
toggle preview:

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

Follow this question

By Email:

Once you sign in you will be able to subscribe for any updates here

By RSS:

Answers

Answers and Comments

Topics:

x64
x16
x16

asked: Jan 19 '12 at 03:13 AM

Seen: 2324 times

Last Updated: Jun 16 '12 at 07:25 PM