- Home /
Socket connection throught javascript
Is there way to create socket connection with javascript? If anyone can post a snippet, it will be great
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.
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 :(
Alright. I'll post some code in a $$anonymous$$ute. :P
also i need some information about calling csharp functions from javascript...
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.
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.
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();
}
}
}
Your answer
![](https://koobas.hobune.stream/wayback/20220613134000im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
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