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
0
Question by user-10779 (google) · May 13, 2011 at 12:30 PM · socketjavascript-specific

Socket connection throught javascript

Is there way to create socket connection with javascript? If anyone can post a snippet, it will be great

Comment
Add comment · Show 4
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 CHPedersen · May 13, 2011 at 12:45 PM 0
Share

Plenty. It's pretty simple. :) I don't have a JavaScript solution, but I'd be happy to provide a C# snippet if you think it'll be helpful.

avatar image user-10779 (google) · May 13, 2011 at 12:48 PM 0
Share

It will be helpful of course, i was going to build connection with csharp at first, but then i failed to call my functions from javascript :(

avatar image CHPedersen · May 13, 2011 at 12:50 PM 0
Share

Alright. I'll post some code in a $$anonymous$$ute. :P

avatar image user-10779 (google) · May 13, 2011 at 01:13 PM 0
Share

also i need some information about calling csharp functions from javascript...

2 Replies

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

Answer by CHPedersen · May 13, 2011 at 01:13 PM

C# does have a specific Socket class (member of System.Net.Sockets) that you can use to instantiate a new Socket. It has a pretty overwhelming bunch of methods. I'm listening for data in my program, so I used a TcpClient instead. I found it to be simpler to use.

The client runs in a thread of its own so that waiting for data to arrive doesn't block the mainthread, causing Unity to hiccup:

using System.Net; using System.Net.Sockets;

public class YourClass {

 private Thread WorkerThread;
 private bool running = false;

 public YourClass()
 {
 }

 public void Start()
 {
     WorkerThread = new Thread(ThreadListener);
     WorkerThread.Start();
 }

 public void Stop()
 {
     running = false;
     WorkerThread.Join();
     WorkerThread = null;
 }

 private void ThreadListener()
 {
     TcpClient client = new TcpClient();
     NetworkStream ns = null;
     int port = 3000;

     try
     {

         client.Connect(new IPEndPoint(IPAddress.Parse("127.0.0.1"), port));

         ns = client.GetStream();

         // Example of how to read data from the client...
         byte[] data;
         data = new byte[1024]; // Could be whatever length you require

         // Wait for the data to arrive, sleep thread continuously until it does
         // But don't wait forever, or thread might deadlock
         int waitCounter = 0;
         while (!ns.DataAvailable && waitCounter < 1000)
         {
             Thread.Sleep(10);
             waitCounter++;
         }

         // Done waiting. Did we exit because data is available, or did we exit because of a timeout?
         if (waitCounter == 1000)
         {
             // 10053 is the Windows Socket error code for when software causes a connection abort, possibly due to a time-out, which is exactly
             // what has happened if the waitCounter reaches 1000
             throw new SocketException(10053);
         }

         running = true;
         // Incoming complete. Enter read loop.

         while (running)
         {
             // Read data chunk
             ns.Read(data, 0, data.Length);

             // Then parse values out of your data chunk typically using static methods 
             // in the BitConverter class
             int example = BitConverter.ToInt32(data, 0); // Makes an integer out of the first 4 bytes read
         }
     }
     catch (InvalidOperationException InvOpEx)
     {
         Debug.Log("TCP exception: " + InvOpEx.Message);
     }
     catch (SocketException SockEx)
     {
         Debug.Log("Socket exception: " + SockEx.Message);
     }
     finally
     {
         if(ns != null)
             ns.Close();
         client.Close();
     }
 }

}

You can terminate the thread from the mainthread by calling Stop(). Beware that the above is a little simplified - I removed a few things not relevant to the example. You'll probably be wise to implement your own improvements, such as not hardcoding the port and IP-adress, for instance.

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 Eric5h5 · May 14, 2011 at 06:05 PM 0
Share

Just to be nitpicky, the Socket class isn't C#'s, it's .NET's. Any language that uses .NET can use it, including JS.

avatar image
1

Answer by Eric5h5 · May 14, 2011 at 05:57 PM

All .NET functions work with all languages that use .NET, including Unityscript. Here's Christian's code translated. I haven't tested it, but it does compile.

import System; import System.Threading; import System.Net; import System.Net.Sockets;

class YourClass {

 private var WorkerThread : Thread;
 private var running = false;

 function YourClass()
 {
 }

 function Start()
 {
     WorkerThread = new Thread(ThreadListener);
     WorkerThread.Start();
 }

 function Stop()
 {
     running = false;
     WorkerThread.Join();
     WorkerThread = null;
 }

 private function ThreadListener()
 {
     var client = new TcpClient();
     var ns : NetworkStream;
     var port = 3000;

     try
     {

         client.Connect(IPEndPoint(IPAddress.Parse("127.0.0.1"), port));

         ns = client.GetStream();

         // Example of how to read data from the client...
         var data = new byte[1024]; // Could be whatever length you require

         // Wait for the data to arrive, sleep thread continuously until it does
         // But don't wait forever, or thread might deadlock
         var waitCounter = 0;
         while (!ns.DataAvailable && waitCounter < 1000)
         {
             Thread.Sleep(10);
             waitCounter++;
         }

         // Done waiting. Did we exit because data is available, or did we exit because of a timeout?
         if (waitCounter == 1000)
         {
             // 10053 is the Windows Socket error code for when software causes a connection abort, possibly due to a time-out, which is exactly
             // what has happened if the waitCounter reaches 1000
             throw SocketException(10053);
         }

         running = true;
         // Incoming complete. Enter read loop.

         while (running)
         {
             // Read data chunk
             ns.Read(data, 0, data.Length);

             // Then parse values out of your data chunk typically using static methods 
             // in the BitConverter class
             var example = BitConverter.ToInt32(data, 0); // Makes an integer out of the first 4 bytes read
         }
     }
     catch (InvOpEx : InvalidOperationException)
     {
         Debug.Log("TCP exception: " + InvOpEx.Message);
     }
     catch (SockEx : SocketException)
     {
         Debug.Log("Socket exception: " + SockEx.Message);
     }
     finally
     {
         if(ns != null)
             ns.Close();
         client.Close();
     }
 }

}

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

No one has followed this question yet.

Related Questions

Socket IO server 1 Answer

SocketPolicyServer Issues 2 Answers

Display the speed of a Game Object in MPH 1 Answer

2Dimensional Array? 1 Answer

Quit Menu errors 2 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