Wayback Machinekoobas.hobune.stream
May JUN Jul
Previous capture 13 Next capture
2021 2022 2023
1 capture
13 Jun 22 - 13 Jun 22
sparklines
Close Help
  • 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
1
Question by LastTemplar · Jan 19, 2012 at 03:13 AM · socketarduino

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 ;)

Comment
Add comment · Show 3
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 LastTemplar · Jan 19, 2012 at 11:35 AM 0
Share

anyone? please?

avatar image Narmer LastTemplar · Apr 18, 2016 at 04:27 PM 0
Share

Have you found an answer? I am trying to make an async client in Unity communicating with Java socket server and I am struggling.

avatar image raodun · Jun 26, 2013 at 01:55 PM -1
Share

I have the error too. error CS0117: System.Threading.ThreadPool' does not contain a definition for GetAvailableThreads' who knows?

1 Reply

· Add your reply
  • Sort: 
avatar image
0

Answer by mcroswell · Jun 16, 2012 at 06:36 PM

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

Comment
Add comment · 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

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.

Follow this Question

Answers Answers and Comments

7 People are following this question.

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

Related Questions

Is it possible to control a game with an Android phone without Unity? 1 Answer

Unity with Arduino+WiFly 0 Answers

Yet another socket-and-crossdomain-policy question 1 Answer

SSL over socket Remote Certificate Not Available 1 Answer

Unity with sockets c# 0 Answers


Enterprise
Social Q&A

Social
Subscribe on YouTube social-youtube Follow on LinkedIn social-linkedin Follow on Twitter social-twitter Follow on Facebook social-facebook Follow on Instagram social-instagram

Footer

  • Purchase
    • Products
    • Subscription
    • Asset Store
    • Unity Gear
    • Resellers
  • Education
    • Students
    • Educators
    • Certification
    • Learn
    • Center of Excellence
  • Download
    • Unity
    • Beta Program
  • Unity Labs
    • Labs
    • Publications
  • Resources
    • Learn platform
    • Community
    • Documentation
    • Unity QA
    • FAQ
    • Services Status
    • Connect
  • About Unity
    • About Us
    • Blog
    • Events
    • Careers
    • Contact
    • Press
    • Partners
    • Affiliates
    • Security
Copyright © 2020 Unity Technologies
  • Legal
  • Privacy Policy
  • Cookies
  • Do Not Sell My Personal Information
  • Cookies Settings
"Unity", Unity logos, and other Unity trademarks are trademarks or registered trademarks of Unity Technologies or its affiliates in the U.S. and elsewhere (more info here). Other names or brands are trademarks of their respective owners.
  • Anonymous
  • Sign in
  • Create
  • Ask a question
  • Spaces
  • Default
  • Help Room
  • META
  • Moderators
  • Explore
  • Topics
  • Questions
  • Users
  • Badges