Socket Io Unity



A minimalistic, single-file client implementation. Since socket-io is a dying technology, and the specification is quite complicated, bugs on either side might just never get fixed at any time. A single file approach is at least easier to tune, expand and debug. I have found this link to use socket.io in unity, but I am unable to configure it. This is my Unity code: using UnityEngine; using System.Collections; public class Test: MonoBehaviour void S. Get the Client Server Integration using Socket.IO package from CYKO and speed up your game development process. Find this & other Network options on the Unity Asset Store. Sprint into Spring Sale is on: Get 50% off top assets and score extra savings with coupon code SPRING2021! Client Server Integration using Socket.IO - Unity 3D.

Like many homes, my kids and I enjoy playing video games together. At this stage of life, my kids especially playing games like Minecraft or Roblox. As I continue to explore the Unity ecosystem, I decided to look into using NodeJs to implement a playground for my kids in a Unity game. In this post, I’ll outline the major ideas I used to create my prototype. In the future, hope this prototype evolves into a multiplayer tank shooter game.

This blog post will assume a working knowledge of Unity. To start things off, I installed the following tools from the Unity Asset store. If you’re interested in getting started with Unity, check out their learning materials here.

https://assetstore.unity.com/packages/tools/network/socket-io-for-unity-21721(by Fabio Panettieri)
https://assetstore.unity.com/packages/tools/input-management/json-net-for-unity-11347
(from Parent Element LLC)

The SocketIO asset includes a sample scene outlining the common setup.

If you’re interested in inspecting a finished sample, please visit the following GitHub link.
https://github.com/michaelprosario/tanks

I did test this SocketIO in an Android mobile environment too. Unfortunately, it didn’t work well. These patterns seem to work fine with Unity desktop experiences. There may be additional edits I need to do to get it working.

While learning this pairing of Unity 3D and SocketIO, I found the following video series very helpful too. Thank you Adam Carnagey!

To build our prototype, let’s kick things off by building our server. This server will leverage NodeJs. In your server working directory, create a package.json like the following:

Next, let’s implement our tank-server.js. This code will instantiate a server using web sockets at port 4567.

Implementing the Unity client controller

In your Unity solution, you will go through a process of creating a scene and defining your environment. In this section, we’ll outline the major parts of implementing the socket io prefab and the controller script.

  1. Like any game experience, we start with creating a new unity project, adding a scene, making a terrain, and player objects.
  2. Install the Unity SocketIO package from the asset store. https://assetstore.unity.com/packages/tools/network/socket-io-for-unity-21721

  3. After the package installs, inspect the README.txt and sample scene to get a feel of how you layout your scene and configure the references to your server. I recommend that you layout your scene in a similar fashion.

  4. For my solution, I started by crafting a few command and query objects to communicate state changes of my players to the server. We’ll also review response objects to receive data from the server.

In this interface, we model some of the key operations of our scene. In your implementation of the scene, you will need to provide concrete implementations of these operations. You can see my simple implementation here:
https://github.com/michaelprosario/tanks/blob/master/Assets/Scenes/SceneOneView.cs

At this point, we’re ready to talk through the main socket controller script. I’m only going to highlight the key themes of the script. You can inspect the whole body of the script here. https://github.com/michaelprosario/tanks/blob/master/Assets/Scenes/SceneOneSocketController.cs

This controller depends upon the socketIO and a reference to the current player. The controller keeps a reference to the view interface so that messages from the server can be routed to scene actions.

When we start the controller, we give our player an identity. Next, we resolve the references for the view and the socket IO component. Finally, we connect various socket events to handlers. We also let the server know that a new player started.

Unity Node Js

The following methods enable us to send commands and query requests to the server.

To announce a new player, we leverage the following method.

As we move around, we let the server know how we’re moving. My gut says that I need to find a more optimal way to communicate this kind of state. I think it will work fine for a small number of players on a local network.

The following handlers map responses from the socket server to view actions.

Hope this post gives you a general overview of how to start a multi-player Unity scene using NodeJS and SocketIO. We love to hear from our readers. Please share a comment and let us know what you’re building!

You're browsing the documentation for v3.x. For v4.x, click here.

Besides emitting and listening to events, the Socket instance has a few attributes that may be of use in your application:

Socket#id

Each new connection is assigned a random 20-characters identifier.

This identifier is synced with the value on the server-side.

Socket#connected

This attribute describes whether the socket is currently connected to the server.

Lifecycle

Events

The Socket instance emits three special events:

Please note that since Socket.IO v3, the Socket instance does not emit any event related to the reconnection logic anymore. You can listen to the events on the Manager instance directly:

More information can be found in the migration guide.

connect

This event is fired by the Socket instance upon connection and reconnection.

Please note that you shouldn’t register event handlers in the connect handler itself, as a new handler will be registered every time the Socket reconnects:

connect_error

This event is fired when:

  • the low-level connection cannot be established
  • the connection is denied by the server in a middleware function

In the first case, the Socket will automatically try to reconnect, after a given delay.

Socket Io Unity

In the latter case, you need to manually reconnect. You might need to update the credentials:

disconnect

This event is fired upon disconnection.

Socket Io Unity

Here is the list of possible reasons:

Socket Io Unity Play

ReasonDescription
io server disconnectThe server has forcefully disconnected the socket with socket.disconnect()
io client disconnectThe socket was manually disconnected using socket.disconnect()
ping timeoutThe server did not send a PING within the pingInterval + pingTimeout range
transport closeThe connection was closed (example: the user has lost connection, or the network was changed from WiFi to 4G)
transport errorThe connection has encountered an error (example: the server was killed during a HTTP long-polling cycle)

In the first two cases (explicit disconnection), the client will not try to reconnect and you need to manually call socket.connect().

Socket.io Unity 2019

In all other cases, the client will wait for a small random delay and then try to reconnect:

Socket.io Unity 2018

Note: those events, along with disconnecting, newListener and removeListener, are special events that shouldn’t be used in your application:

Complete API

The complete API exposed by the Socket instance can be found here.