itisnajim / socketiounity Goto Github PK
View Code? Open in Web Editor NEWA Wrapper for socket.io-client-csharp to work with Unity.
License: MIT License
A Wrapper for socket.io-client-csharp to work with Unity.
License: MIT License
Hi @itisnajim
I'm using socket.EmitAsync(message, response => {
** assigning some data in here**
bool Foo = response.getValue();
}, params);
if (Foo is true )
{
DoMyActionBasedOnFoo();
}
However, depending on how heavy the task is my if statement is executed earlier than Foo is assigned, resulting in nullreferenceExceptions etc.
Do you know how I can assure the EmitAsync method is fully done and back on the right thread? so the order of execution is as I want?
I'm tryring your sample code and i got this error
Severity Code Description Project File Line Suppression State Error CS0012 The type 'JsonElement' is defined in an assembly that is not referenced. You must add a reference to assembly 'System.Text.Json, Version=6.0.0.4
and
Severity Code Description Project File Line Suppression State Error CS0411 The type arguments for method 'SocketIOResponse.GetValue<T>(int)' cannot be inferred from the usage. Try specifying the type arguments explicitly
from this line of code.
ReceivedText.text += "Received On " + name + " : " + response.GetValue().GetRawText() + "\n";
Hello, I am trying to convert the object from the server into a list element, but I have not been successful. Here is my code.
`
socket.OnUnityThread("friendsStatus", (data) =>
{
//var friends = JsonConvert.DeserializeObject<List>(data.GetValue().GetRawText(), new JsonSerializerSettings
//{
// TypeNameHandling = TypeNameHandling.Auto
//});
Debug.Log(data.GetValue()); // Output of the log : [{"indexnumber":2,"status":0},{"indexnumber":3,"status":0}]
});`
How to reach like friends[0].status. Thanks a lot.
Where should I customize 'cors_allowed_origins' for the server
Package manager keep downloading 1.1.3 even with version specification in url
So when i try to build to il2cpp i get this building error:
Mono.Linker.MarkException: Error processing method: 'System.Void System.Text.Json.Nodes.JsonArray::Add(T)' in assembly: 'System.Text.Json.dll'
So this is how i use the code.
As you see i set the JsonSerializer to NewtonsoftJsonSerializer as said in the Readme.
string deviceId = SystemInfo.deviceUniqueIdentifier;
this.socket = new SocketIOUnity(uri, new SocketIOOptions
{
Query = new Dictionary<string, string>
{
{"token", "UNITY" }
}
,
Transport = SocketIOClient.Transport.TransportProtocol.WebSocket
});
var jsonSerializer = new NewtonsoftJsonSerializer();
socket.JsonSerializer = jsonSerializer;
socket.OnConnected += async (sender, e) =>
{
await socket.EmitAsync("register", deviceId);
};
this.socket.OnUnityThread("readyDevice", onReady);
socket.ConnectAsync();
Is it possible to get a version that is whitout System.text.json so it does not need to build that package.
using System.Collections;
using System.Collections.Generic;
using SocketIOClient;
using SocketIOClient.Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using UnityEngine;
using System;
using UnityEngine.SceneManagement;
public class NetworkManager : MonoBehaviour
{
private string server = "http://localhost:3001";
public static SocketIOUnity socket;
// Start is called before the first frame update
void Start()
{
socket = new SocketIOUnity(server, new SocketIOOptions
{
Query = new Dictionary<string, string>
{
{"token", "UNITY" }
}
,
EIO = 4
,
Transport = SocketIOClient.Transport.TransportProtocol.WebSocket
});
socket.JsonSerializer = new NewtonsoftJsonSerializer();
socket.OnConnected += (sender, e) =>
{
Debug.Log("socket.OnConnected");
};
socket.OnPing += (sender, e) =>
{
Debug.Log("Ping");
};
socket.OnPong += (sender, e) =>
{
Debug.Log("Pong: " + e.TotalMilliseconds);
};
socket.OnDisconnected += (sender, e) =>
{
Debug.Log("disconnect: " + e);
};
socket.OnReconnectAttempt += (sender, e) =>
{
Debug.Log($"{DateTime.Now} Reconnecting: attempt = {e}");
};
////
Debug.Log("Connecting...");
socket.Connect();
socket.On("hello", (response) => {
Debug.Log("Receive Hello");
loadnewscene();
});
}
public void loadnewscene()
{
Debug.Log("Changing Scene");
SceneManager.LoadScene("GamePlay");
}
// Update is called once per frame
}
When I tried to use the latest release (V1.1.1.) I get System.Reactive not found errors.
Steps to reproduce:
Tested on:
Unity 2021.3.3 LTS
Unity 2021.2.5
Hi,
I installed the SocketIOUnity
inside my project in order to use websocket.
Whenever the installation process has finished I got all the scripts recompilation in Unity with a console error:
Library/PackageCache/com.atteneder.gltfast@f6c014e6b0/Runtime/Scripts/GltfImport.cs(410,13): error CS0518: Predefined type 'System.IAsyncDisposable' is not defined or imported
I think there is a conflict between SocketIOUnity
and gltfast
somehow.
Do you have a workaround to solve the issue?
Thanks,
Al
The socket.Emit()
function works correctly on the Editor.
My android device receives the messages as expected, but when Emitting from android, nothing shows on the server or elsewhere. The code is the same on the Editor and the Android device.
I'm trying to get socket.io to work in Unity.
On both the client (Unity) and the server (Node) I can see that it was able to connect successfully.
However, the server never receives the "message" event that I'm emitting upon connection.
I don't see any errors.
using UnityEngine;
using System;
public class Test : MonoBehaviour
{
void Start() {
var uri = new Uri("ws://localhost:8090");
var client = new SocketIOUnity(uri);
client.OnConnected += async (sender, e) =>
{
Debug.Log("OnConnected");
await client.EmitAsync("message", "bla"); // client.Emit doesn't work either
};
client.OnError += (sender, e) => {
Debug.Log("OnError: " + e);
};
client.Connect();
}
}
Here's the Node server:
const httpServer = require("http").createServer();
const io = require("socket.io")(httpServer, { cors: true });
io.on("connection", (socket) => {
console.log('connection');
});
io.on("message", (value) => {
console.log('message', value);
});
httpServer.listen(8090);
When we run our socket IO connection on the Unity editor the connection perfecly works and we are connected.
But when we build and run the exact same code to Android (Quest runs on Android) it does not connect.
Strangly the server gets a get request when it tries to connects but no connection is made.
Wrapper code:
using Newtonsoft.Json;
using SocketIOClient;
using SocketIOClient.Newtonsoft.Json;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Threading.Tasks;
using UnityEngine;
namespace Altheria.SocketIo
{
/// <summary>
/// Ah wrapping class to handle SocketIo systems of Altheria as a Device
/// </summary>
public class SocketIoHandeler
{
private static SocketIoHandeler instance = null;
public static SocketIoHandeler Instance
{
get
{
if (instance == null)
{
instance = new SocketIoHandeler();
}
return instance;
}
}
/// <summary>
/// Creates a connection to the websocket server using SocketIo standard.
/// Registers the events to listen to.
/// </summary>
/// <param name="uri">The ip addres of the WebSockt Server</param>
/// <param name="listeners">The Dictionary of event listener name and listener function</param>
public void connect(Uri uri,Dictionary<string, Action<SocketIOResponse>> listeners)
{
connect(uri);
RegisterMulipleSocketListener(listeners);
}
/// <summary>
/// Creates a connection to the websocket server using SocketIo standard.
/// </summary>s
/// <param name="uri">The ip addres of the WebSockt Server</param>
public void connect(Uri uri)
{
string deviceId = SystemInfo.deviceUniqueIdentifier;
this.socket = new SocketIOUnity(uri);
var jsonSerializer = new NewtonsoftJsonSerializer();
socket.JsonSerializer = jsonSerializer;
socket.OnConnected += async (sender, e) =>
{
await socket.EmitAsync("RegisterDevice", deviceId);
};
_ = socket.ConnectAsync();
UnityEngine.Debug.Log(this.socket.Connected);
}
/// <summary>
/// Registers an event Listener for the SocketServer
/// </summary>
/// <param name="listenerKey"> The name of the Socket event</param>
/// <param name="listener">The function that executes when this event gets triggers</param>
public void RegisterSocketListener(string listenerKey, Action<SocketIOResponse> listener)
{
this.socket.OnUnityThread(listenerKey, listener);
}
/// <summary>
/// Registers an dictionary of event Listeners for the SocketServer
/// </summary>
/// <param name="listeners">>The Dictionary of event listener name and listener function</param>
public void RegisterMulipleSocketListener(Dictionary<string, Action<SocketIOResponse>> listeners)
{
foreach (var x in listeners)
{
RegisterSocketListener(x.Key, x.Value);
}
}
public SocketIOUnity socket { get; set; }
public string deviceId { get; set; }
/// <summary>
/// Emits an event to the websocket server
/// </summary>
/// <param name="eventName">The name of the event</param>
/// <param name="data">The data to send to the server</param>
public void Emit(string eventName, params object[] data )
{
this.socket.Emit(eventName, data);
}
}
}
Hi there, I couldn't get it to connect on the Android phone. It works fine in Unity editor. Scripting backend IL2CPP api Compatibility level .Net Framework. I also use server-side codes in another react native application. I don't think there is a problem on the server side. Socket versions Unity side v1.0.0 , server side v4.1.3. I opened a project from scratch and pulled the unity side to v1.1.3 and the server side to v4.5.4, but it still didn't work. I would be glad if you can help.
How to keep the client connected ?
I'm using KyleDulce.SocketIo but it sadly got depreciated, and as soon as I developed deep enough I realized that there is no ping-pong/heartbeeat mechanism, so all clients would disconnected as soon as the time ran out.
could you show me an example to maintain a heart beat ?
I'm using python as the backenet/server, would that be a problem ?
in webgl built, showing nothing
I want to use Auth mode in socketIOOption to check for authentication token. I could not find any example. i look for solution
Try to change socket io server version to v3.x.x, set EIO in sample to 3
Doesn't work =(
P.S. works fine with v4.2.0
Running a very simple server that uses auth according to the documentation here:
https://socket.io/docs/v4/server-socket-instance/#sockethandshake
I have discovered that this plugin has no way to send the auth object needed. Doing it through the query field, as documented for this plugin, leaves a handshake on the server log that looks like this:
connection from a socket
{
headers: { connection: 'keep-alive', host: 'localhost:8000' },
time: 'Mon May 16 2022 14:01:12 GMT-0700 (Pacific Daylight Time)',
address: '::1',
xdomain: false,
secure: false,
issued: 1652734872041,
url: '/third_party//?EIO=4&transport=polling&auth=123',
query: [Object: null prototype] {
EIO: '4',
transport: 'polling',
auth: '123'
},
auth: {}
}
Note how the auth field is empty. Is there some way of filling in that field that is undocumented? I notice that there is no auth option at the Query/EIO/Path/ExtraHeader level, SocketIOOptions, which is where it needs to be.
it worked fine on editor but on Android and IOS emit not work
Removed - solved.
when i connect to localhost with unity it works fine, but when I upload it to my remote server it doesn't work it returns unable to connect to remote server, but when I try to connect with this site "http://amritb.github.io/socketio-client-tool/", it works just fine
import { SocketServer } from "./Classes/Server";
import { WebServer } from "./Web/WebServer";
import express, { Express, Request, Response } from 'express';
const PORT = process.env.PORT || 8080;
// const PORT = 8080;
const http = require('http');
const app: Express = express();
const server = http.createServer(app);
var GameServer = new SocketServer(server);
var AdminServer = new WebServer(app);
server.listen(PORT, () => {
console.log(`Server listening on port ${PORT}`);
});
constructor(server: http.Server) {
this.io = new Server(server, {
cors: {
origin: "*"
}
});
this.DatabaseHandler = new DatabaseHandler();
this.Connections = [];
this.Lobbies = [];
this.io.use(async (socket: Socket, next: any) => {
console.log("Hit!");
.......
});
}
Greetings! I am having so much fun with SocketIOUnity. Thank you very much for this.
I have run into a problem, where I found the child thread keeps running in the background even though the main thread is exited. I tried to manually callSocketIOUnity.Disconnect()
in OnApplicationQuit()
and OnDestroy()
to see if I could destroy the child thread, and it failed to do so. I thereby set SocketIOUnity.Options.Reconnection = false
to stop auto-reconnection to the server and it worked (i.e. not attempting to reconnect to the server).
However, I am not sure if this can kill all background threads. Am I doing anything wrong? Is there any proper way to exit the main thread with all background threads killed?
Thanks again :)
Restarting doesn't help and this is a new project
I'm using unity 2019.4.36f1
I've tried to do the same as you mentioned here
https://share.vidyard.com/watch/F7cBZi1jG2mS4mb8AaVJBG
but it got worth
I got extra four errors
how to fix this ?
im trying use glitch.com server... localhost work but not work for myurl.glitch.me
Thank you for providing us with a useful open source.
First, my development environment.
[node.js server]
"socket.io": "^4.2.0"
[Unity]
Unity Editor : 2021.3.3f1
SocketIOUnity : 1.1.4
When I received the socket event, I expected the result value to be received in json as follows.
{"room" : {"hostIpAddress" : "xxx.x.x.x", "maxPlayer" : "3", "currentPlayer" : "M-A2-UtAAzhZYS93AAAB"}}
But the actual result is wrapped in an array
[{"room" : {"hostIpAddress" : "xxx.x.x.x", "maxPlayer":"3", "currentPlayer" : "M-A2-UtAAzhZYS93AAAB"}}]
Is this a bug? If I'm using it wrong, how can I fix it?
Thanks.
Does this library supports wss?
With WS all works great, but with wss i can't connect to server.
After successfully connecting to a test server with the example client code via the Unity editor in run mode, something peculiar happens after stopping.
For some reason the socket.io process just keeps going, despite the fact I stopped the program. I have to kill Unity to make this stop.
I tried to add this code, which should kill the socket when the editor stops, but that doesn't seem to be the case:
private void OnApplicationQuit()
{
socket.Disconnect();
}
using System;
using System.Collections.Generic;
using SocketIOClient;
using SocketIOClient.Newtonsoft.Json;
using UnityEngine;
using UnityEngine.UI;
using Newtonsoft.Json.Linq;
using UnityEngine.SceneManagement;
public class ClientSocketManager : MonoBehaviour
{
public SocketIOUnity socket;
public Text ReceivedText;
public Image t;
// Start is called before the first frame update
void Start()
{
//TODO: check the Uri if Valid.
var uri = new Uri("http://localhost:3000");
socket = new SocketIOUnity(uri, new SocketIOOptions
{
Query = new Dictionary<string, string>
{
{"token", "UNITY" }
}
,
EIO = 4
,
Transport = SocketIOClient.Transport.TransportProtocol.WebSocket
});
socket.JsonSerializer = new NewtonsoftJsonSerializer();
///// reserved socketio events
socket.OnConnected += (sender, e) =>
{
Debug.Log("connected");
SceneManager.LoadScene("GameScene");
};
socket.Connect();
}
}
this is my code. very simple, LoadScene does not work even do the callback is called ( debug.log connected works )
I can connect from the Editor and from the build for Window and it works perfectly, but I can't connect from Android at all and it doesn't respond.
I already add permission to use internet from the AndroidManifest.xml.
I am using socket.io: 4.5.1 from my Express.js server.
Verify that it is not the HTTPS and start a service with NGROK with the HTTPS certificate and I got the same nothing
I deployed my nodejs server in Heroku. It is connecting with the unity but it is not sending and receiving any data from the server.
In Unity I used like this for connecting to my server.
`
var uri = new Uri("ws://herokuapp name<>.herokuapp.com");
//Creating a socket
socket = new SocketIOUnity(uri, new SocketIOOptions
{
Query = new Dictionary<string, string>
{
{"token", "UNITY" }
}
,
EIO = 4
,
Transport = SocketIOClient.Transport.TransportProtocol.WebSocket
});
`
The output I got using the library works in android build but not in ios build. I tried to trace the error.
_transport = new WebSocketTransport(_clientWebsocket, Options, JsonSerializer); It doesn't go below this line, I think the error may originate from here. while (_isConnectCoreRunning) is looping continuously but I am not getting any ping or pong or on connected logs.
Also I got this warning in xcode but I dont found any solution or relevant,
3 UnityFramework 0x0000000107856038 _ZN14il2cpp_baselib31Baselib_SystemSemaphore_AcquireENS_30Baselib_SystemSemaphore_HandleE + 28
4 UnityFramework 0x000000010783b45c ZN6il2cpp2vm13MetadataCache16GetGenericMethodEPK10MethodInfoPK17Il2CppGenericInstS7 + 384
5 UnityFramework 0x000000010781f11c _ZL25GetGenericMethodFromIndexi + 144
6 UnityFramework 0x000000010781ec1c _ZL29GetMethodInfoFromEncodedIndexj + 44
7 UnityFramework 0x000000010781ea20 _ZN6il2cpp2vm14GlobalMetadata25InitializeRuntimeMetadataEPmb + 96
8 UnityFramework 0x0000000108512160 UnityThread_FixedUpdate_mC11898F4E00DF830D8B2A93BD2E1E85332AF5CF0 + 56
9 UnityFramework 0x0000000107834ae4 ZN6il2cpp2vm7Runtime15InvokeWithThrowEPK10MethodInfoPvPS5 + 100
10 UnityFramework 0x000000010783492c _ZN6il2cpp2vm7Runtime6InvokeEPK10MethodInfoPvPS5_PP15Il2CppException + 84
11 UnityFramework 0x0000000106e0fabc _Z23scripting_method_invoke18ScriptingMethodPtr18ScriptingObjectPtrR18ScriptingArgumentsP21ScriptingExceptionPtrb + 112
12 UnityFramework 0x0000000106e1b668 _ZN19ScriptingInvocation6InvokeEP21ScriptingExceptionPtrb + 120
13 UnityFramework 0x0000000106e2a1e0 _ZN13MonoBehaviour16CallUpdateMethodEi + 272
14 UnityFramework 0x0000000106c8c520 _ZN20BaseBehaviourManager12CommonUpdateI21FixedBehaviourManagerEEvv + 228
15 UnityFramework 0x0000000106d3ad54 _Z17ExecutePlayerLoopP22NativePlayerLoopSystem + 100
16 UnityFramework 0x0000000106d3ad94 _Z17ExecutePlayerLoopP22NativePlayerLoopSystem + 164
17 UnityFramework 0x0000000106d3aff0 _Z10PlayerLoopv + 272
18 UnityFramework 0x00000001072a1ca4 _ZL19UnityPlayerLoopImplb + 112
19 UnityFramework 0x00000001069c2d64 -[UnityAppController(Rendering) repaint] + 84
20 UnityFramework 0x00000001069c2cf4 -[UnityAppController(Rendering) repaintDisplayLink] + 76
21 QuartzCore 0x000000018f5c7fa4 E0E47B5D-2805-361D-88C4-875002B0244D + 167844
22 QuartzCore 0x000000018f6f53b8 E0E47B5D-2805-361D-88C4-875002B0244D + 1401784
23 UIKitCore 0x0000000190723498 59CBC9B5-30AE-396E-A269-A986640001BC + 6628504
24 UIKitCore 0x0000000190d6f410 59CBC9B5-30AE-396E-A269-A986640001BC + 13231120
25 UIKitCore 0x0000000190d6e5dc 59CBC9B5-30AE-396E-A269-A986640001BC + 13227484
26 CoreFoundation 0x000000018dfd1f34 725E49F4-653B-39BF-9A7A-8A3250911ECB + 876340
27 CoreFoundation 0x000000018dfde30c 725E49F4-653B-39BF-9A7A-8A3250911ECB + 926476
28 CoreFoundation 0x000000018df621d0 725E49F4-653B-39BF-9A7A-8A3250911ECB + 418256
29 CoreFoundation 0x000000018df77b8c 725E49F4-653B-39BF-9A7A-8A3250911ECB + 506764
30 CoreFoundation 0x000000018df7cec0 CFRunLoopRunSpecific + 612
31 GraphicsServices 0x00000001c7fd3368 GSEventRunModal + 164
32 UIKitCore 0x000000019047286c 59CBC9B5-30AE-396E-A269-A986640001BC + 3807340
33 UIKitCore 0x00000001904724d0 UIApplicationMain + 340
34 UnityFramework 0x00000001069c2898 -[UnityFramework runUIApplicationMainWithArgc:argv:] + 92
35 Barbut 0x0000000100d4bcac main + 60
36 dyld 0x00000001ac79e960 7B63C573-6161-3B33-A3A2-9944BA59722F + 88416
I've been tested on oneplus8 then it seems to not working
Hi, how to connect to different namespaces?
I have a problem using namespaces and implementing them in the client, how to implement them in the client
Please help, any help would be helpful
Thanks
Currently I'm working on an application for the Hololens 2.
I created a small NodeJS server which watches a folder for new added files. This server then sends with Socket IO this data to the Unity client. This works perfectly in the editor. However, When I have a build on my Hololens 2. The application doesn't want to connect to my pc.
Steps to reproduce:
Do you know what might cause this issue or how I can solve it?
many thanks
Hi there :). Thank you for creating this library! Having lots of issues with socket-io assets for Unity, been struggling for over a week due to WebSocketSharp not playing nice with socket.io v4.
I've added this package successfully, but the code files aren't actually added to the project. So I can't actually use anything. So, I manually copied the files into Assets, but then I get tons of errors unless I also import the "libs" folder. But then further down the rabbit hole I go, because once I import the "libs" folder, I get duplicated assembly errors. And if I try to delete the package from PackageCache, nothing works anymore :(. Any suggestions are welcome! I'm on Unity 2021.3 BTW.
May you implement a version for WebGL or intent to do in future? I
I didn't see NewtonsoftJsonSerializer being removed from the library. Does it now mean it isn't nessesary anymore or was there any other reason for its removal? I think the Readme is now a bit outdated.
Hi! I'm getting this error after I add the package. It seems that Unity includes Newtonsoft.Json.dll by default, and I don't see a way how I can import yours without it.
Here's the full text of the error:
Multiple precompiled assemblies with the same name Newtonsoft.Json.dll included on the current platform. Only one assembly with the same name is allowed per platform. (/...../Library/PackageCache/com.itisnajim.socketiounity@9068aafaf2/Runtime/libs/Newtonsoft.Json Editor/Newtonsoft.Json.dll)
It's not working with IL2CPP build on Android, working fine with Mono build, but we can't use Mono because Unity doesn't support Arm64 build with Mono.
socket.to(room).emit("event","message") cant send the data to the Unity Client
Library\PackageCache\com.itisnajim.socketiounity@47d10f6\Runtime\SocketIOClient\Transport\SystemNetWebSocketsClientWebSocket.cs(30,18): error CS0433: The type 'Subject' exists in both 'System.Reactive.Linq, Version=2.2.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35' and 'System.Reactive, Version=5.0.0.0, Culture=neutral, PublicKeyToken=94bc3704cddfc263'
I get this error on import
After getting help from a friend, I discovered that the reason I was having such issues using this plugin's auth methodology was because it's using an older version of socket.io-client-csharp. The newer version, updated in March, allows for authentication middleware support, which I need!
See the fix here:
doghappy/socket.io-client-csharp#266
Would it be possible to update SocketIOUnity to support socket.io-client-csharp 3.0.6?
Hello i have a problem
when i use your plugin i have a double connection on my server
do you have any idea to fix that?
A declarative, efficient, and flexible JavaScript library for building user interfaces.
๐ Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. ๐๐๐
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google โค๏ธ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.