Unity C# Socket.IO Client
Unity client and Server commnication.

Unity C# Socket.IO Client

Pre-requisite

So, Here is the 3rd Part of the series. Link for Part-1 and Part-2

Steps required for the Unity C# client setup:

  • Perspective of Socket.IO
  • Download and Create Project
  • Install Socket.IO Library
  • Write Client-Side C# Code
  • Test The Code

Perspective of Socket.IO

Socket.IO is a useful tool that can help your Unity3D C# client connect and communicate messages with a server. With Socket.IO, you can establish a reliable and efficient connection between your client and the server, and exchange information seamlessly. This can be especially helpful if you're developing an application or game that requires real-time communication. By using Socket.IO in your Unity3D C# client, you can easily transmit data back and forth with the server, and ensure that your users have a smooth and responsive experience. So if you're looking to create a high-quality app or game, Socket.IO is definitely worth considering!

Download and Create Project

Download and install Unity3D: Visit the Unity website and download the latest version of Unity3D. Follow the installation instructions to install the software on your computer.

Create a new project: In the Unity3D window, click "New" to create a new project. Choose a name for your project, and select a location to save the project files. You can check my project details in the image FOCUS ON RED LINES:

Unity HUB and project creation
Project Creation From Unity HUB

Select a template: Unity3D provides a variety of templates to help you get started. Choose a template that's closest to the type of project you want to create. For example, if you want to create a 2D game, choose the 2D template.

Add game objects: In Unity3D, game objects are the building blocks of your game. You can add game objects to your scene by selecting "GameObject" > "Create Empty" from the menu bar. You can then add components to the game object to define its behavior.

We are all set for the client side with a unity base project. Let's install the socket.io package for the client side from this link.

  1. In Unity, open the Package Manager by selecting "Window" > "Package Manager" from the menu bar.
  2. Click the "+" button in the top left corner of the Package Manager window and select "Add package from git URL".
  3. Enter the URL of the GitHub repository
  4. Click "Add" and wait for Unity to import the package. This may take a few minutes, depending on the size of the package.
  5. Once the package is imported, we can start using it in our Unity project. You can access the package's assets, scripts, and other components through the Project window.

Create a script with "SocketIOClientExample".

No alt text provided for this image
SoketIO Client C# Script.

Add the following namespaces in the script.

using System;
using System.Collections.Generic;
using SocketIOClient;
using SocketIOClient.Newtonsoft.Json;
using UnityEngine;
using UnityEngine.UI;
using Newtonsoft.Json.Linq;        

Create an object of socket.io client and link to the server inside the class. I will be using a local host.

public SocketIOUnity socket
public string serverUrlLink = "https://localhost:3000";;        

Your script will look like this.

using System
using System.Collections.Generic;
using SocketIOClient;
using SocketIOClient.Newtonsoft.Json;
using UnityEngine;
using UnityEngine.UI;
using Newtonsoft.Json.Linq;

public class SocketIOClientExample : MonoBehaviour
{
? ? public SocketIOUnity socket;
? ? public string serverUrlLink = "https://localhost:3000";
? ? void Start()
? ? {? ? ? ? 
? ? }
? ? void Update()
? ? {? ? ? ?
? ? }? ?
}        

Add the following code step by step inside the Start function

Create Uri and initialize the socket object with uri.

var uri = new Uri(serverUrlLink);? ? ? ?
socket = new SocketIOUnity(uri);?        

Create the connection object and bind the lambda function or Action callback:

socket.OnConnected += (sender, e) => 
{
 ? ? Debug.Log("socket.OnConnected");
};        

Register for the custom event:

socket.On("message", response =>
{
? ? ?Debug.Log("Event" + response.ToString());
? ? ?Debug.Log(response.GetValue<string>());
});        

Call the object for connection:

socket.Connect();        

Your Start function will look like this.:

void Start()
? ? {
? ? ? ? var uri = new Uri(serverUrlLink);? ? ? ??
? ? ? ? socket = new SocketIOUnity(uri); ? ? ? ? ? ? ?


? ? ? ? socket.OnConnected += (sender, e) =>
? ? ? ? {
? ? ? ? ? ? Debug.Log("socket.OnConnected");
? ? ? ? };


? ? ? ? socket.On("message", response =>
? ? ? ? {
? ? ? ? ? ? Debug.Log("Event" + response.ToString());
? ? ? ? ? ? Debug.Log(response.GetValue<string>());
? ? ? ? });


? ? ? ? socket.Connect();
? ? }        

To call the event on the server side you can write the code like this:

void Update()
{
? ? if (Input.GetKeyDown(KeyCode.Space))
? ? {
? ? ? socket.EmitAsync("message", "Hello, server!"); // replace with your message
? ? }
}        

We also need to dispose of the socket connection on closing or when we don't need the connection.

void OnDestroy()
{
? ?socket.Dispose();
}        

Finally, We can test our script after running the server. It's working for me. Press the Space bar to send the message.

No alt text provided for this image
Testing of the code.

#unity3d #unitydeveloper #socket #clientserver #csharp #multiplayer

Srikanth developer

Unity 3d Developer at Freelance (Self employed)

2 个月

does it work.

回复
André Felipe Siqueira

?? Game Developer | Unity C# | Unreal C++

6 个月

Very good library!!

Vijay Aditya B.

Lead Software Engineer @ TEKsystems | Azure PAAS, .Net Core, React.js, MVC. ex-TCS, ex-Infosys, ex-Capgemini, ex- Hcl, ex-Seanergy, ex-InnovateApps

7 个月

Thanks a lot, got stuck while playing with Mediapipes body tracking. let me try this I used Sockets instead SocketsIO to connect , with this post I realized that.

回复
Adnan Shaukat

Unity Developer at GameStake Technologies | PC & Mobile | AAA | Multiplayer | Hypercasual

2 年

Hey, thanks for the read. Will definitely look at it By the way, what are you using for real-time position and physics syncing? or is it just the flow of meta-data for now?

要查看或添加评论,请登录

Muhammad Afzaal的更多文章

社区洞察

其他会员也浏览了