How do I...
... Connect to a server?
This is an example how your script could look to connect to the default namespace and reconize when the connect succeeded:
SocketIOClient sio; //Assigned via inspector
void Start()
{
sio.D.On("connect", (p) =>
{
Debug.Log("Connected!");
});
sio.Connect();
}
Connect to a specific server
You can set the target server address in the inspector or pass it while connecting:
[...]
sio.Connect("https://backend.example.com");
[...]
Change the Path to the server
If your server is running on a non-standard path, you can pass it using the server address. Please do not confuse this with namespaces! This is the client implementation for this specific feature.
[...]
sio.Connect("https://backend.example.com/mysocket.io/");
[...]
Use a different port
If your server is running on a non-standard port, you can pass it using the server address.
[...]
sio.Connect("https://backend.example.com:1234");
[...]
Use HTTP without encryption
Please don't do that. Its not 19XX anymore. However this is totally possible:
[...]
sio.Connect("http://backend.example.com");
[...]
All server address options
Above are some examples, but there is more: The serverAddress allows to specify the protocol, hostname, port, path and query parameters in one string.
The Socket.IO-Address has to be entered in an URI-Format without protocol:
If using standard ports (Insecure: tcp/80, secure: tcp/443) you do not need to enter a port.
If using the standard socket.io path (/socket.io/) you do not need to specify a path. WARNING: Paths are not the same as namespaces! A path is what you enter into the path-option on the server side.
Possible valid values / combinations could be:
- https://some.server.org
- http://some.server.org
- https://some.server.org:1234
- http://some.server.org?someLoadbalancerHint=abc
- https://some.server.org:1234/otherpath/
- https://some.server.org:1234/otherpath/?someLoadbalancerHint=abc
... Access a namespace
Socket.IO allows to connect to multiple namespaces using one connection. There is always the default namespace ("/"), and you can connect additional namespaces.
Our PLUS-Asset also implements this, which is also the reason that you need to access "D" (for DefaultNamespace) instead of directly subscribing / emitting events on the client instance.
Default Namespace
As simple as sio.DefaultNamespace
or even shorter sio.D
Other namespaces
This is not much more of a hassle: sio.GetNamespace("/otherNamespace")
Other ways to work with namespaces
SocketIOClient sio; //Assigned via inspector
void Start()
{
SocketIONamespace nsAdmin = sio.GetNamespace("/admin");
nsAdmin.On("connect", (sioEvent) =>
{
Debug.Log("Connected to admin namespace!");
//you can also send to other - e.g. the default - namespaces form here
sio.D.Emit("ServerWillShutdown");
//or
sio.D.GetNamespace("/whatever").Emit("ServerWillShutdown");
//now emit to the admin namespace
nsAdmin.Emit("ShutdownServer");
//The coolest thing is, you can create universal callbacks because you will always have a reference back to the namespace from the event itself
sioEvent.Namespace.Emit("AnotherEvent");
});
sio.Connect();
}
... Subscribe to events
For these examples, we assume you already connected and the Client is referenced in "sio".
Subscribe to events
The code example is assumed to run in Start()
sio.D is a shorthand to sio.GetNamespace("/")
//Single payload events can be subscribed using generics
sio.D.On<string>("SinglePayloadEventName", (payload) => {
});
//If you got multiple payloads, this is also possible but requires a slightly different API. Now assuming, payload #1 is a string and #2 is an integer:
//This is what you receive, if the server does this: socket.Emit("MultiPayloadEventName", "some string", 135);
sio.D.On("MultiPayloadEventName", (sioEvent) => {
Debug.Log("Payload 1: " + sioEvent.GetPayload<string>(0));
Debug.Log("Payload 2*2= " + sioEvent.GetPayload<int>(1) * 2);
});
//Maybe the event is an acknowledgement? This is now also possible:
sio.D.On("SomeACKEventName", (sioEvent) => {
if (sioEvent.callback != null) {
object[] response = new string[] { "Some example text" };
e.callback.Invoke(response); //this sends the acknowledgement back to the server
}
});
Unsubscribe from an event
If you register a callback without using a lambda expression and not through a generic "On" call, you can unsubscribe again:
//Create a clalback function
void ProcessSomeEvent(object[] payload) => {
if (payload != null) {
foreach(var p in payload) Debug.Log(p.toString());
}
}
//Register the callback
sio.D.On("SomeEvent", ProcessSomeEvent);
//unregister this specific callback again
sio.D.Off("SomeEvent", ProcessSomeEvent);
You can also unregister all callbacks form an event - This also removes the generic registrations:
//Let's register using a generic "On"
sio.D.On<string>("SinglePayloadEventName", (payload) => {
Debug.Log(payload);
});
//And then clear all registrations on the event
sio.D.RemoveAllListeners("SinglePayloadEventName");
Subscribe for single execution
If you only need to wait for a specific event and fire the callback once, you can make this even easier:
sio.D.Once<string>("SinglePayloadEventName", (payload) => {
//This callback will only fire once
Debug.Log(payload);
});
... Emit events
Simple events (Single Payload)
The following code can be run wherever you need to emit events.
A payload must always be serializable by Json.Net or a binary value in form of a byte[]
If you hand Emit an array as payload, the elements will be sent as individual payloads! See next section.
//Some simple examples
sio.D.Emit("EventWithoutPayload");
sio.D.Emit("EventWithSimplePayload", "A string payload");
sio.D.Emit("EventWithSimpleIntPayload", 1234);
Complex events (multiple payloads)
Multiple payloads are also possible:
List<string> list = new List<string>();
list.Add("a string as first payload"); //string1
list.Add("another string as second payload"); //string2
sio.D.Emit("EventWithMultiplePayloads", list.toArray());
The server side using Javascript will access the payloads like
io.on("EventWithMultiplePayloads", (string1, string2) => {
[... ]
});
... work with complex data structures
This is where the PLUS asset gets interesting: You can use any object, which can be serialized by Json.Net and pass it to a generic "Emit
Just make sure, that your data type can be serialized.
For example classes with recursions, like Transforms, can not be serialized. Create your own data classes or structs if required.