Giter VIP home page Giter VIP logo

colyseus-unity-sdk's Introduction



Discussion forum

Multiplayer Framework for Node.js.
View documentation

Colyseus is an Authoritative Multiplayer Framework for Node.js, with SDKs available for the Web, Unity, Defold, Haxe, Cocos and Construct3. (See official SDKs)

The project focuses on providing synchronizable data structures for realtime and turn-based games, matchmaking, and ease of usage both on the server-side and client-side.

The mission of the framework is to be a standard netcode & matchmaking solution for any kind of project you can think of!

Key features:

  • WebSocket-based communication
  • Simple API in the server-side and client-side.
  • Automatic state synchronization from server-to-client (delta compressed)
  • Matchmaking clients into game rooms/sessions
  • Scale vertically or horizontally

See public roadmap for future plans.

🚀 Quickstart

Create a bare-bones Colyseus server by using npm create colyseus-app@latest:

npm create colyseus-app@latest my-colyseus-server
cd my-colyseus-server
npm start

Sponsors

The sustainability of the project relies on Colyseus Cloud subscriptions and sponsorships. If you are not using Colyseus Cloud, please consider sponsoring the project 💖

Contributors ✨

Thanks goes to these wonderful people (emoji key):


Aymeric Chauvin

💬 💡

Brian Hay

🖋

Damian A. Pastorini

💬 📖 🐛

Darek Greenly

💬 🐛 💻

David Rydwanski

💬 💻

Dr. Burton

🧑‍🏫

Endel Dreyer

💻 📖 💡

Enriqueto

💼

Fazri Zubair

💼

Federico

🐛 💻

James Jacoby

💬 💡 🖋

Jonas Voland

💬 🐛 💻 🤔 💡

Kyle J. Kemp

💬 🐛 💻 🤔

Luke Wood

💬 🐛 💻

Milad Doorbash

🐛 💻

Nikita Borisov

🐛 💻 💼 🤔

Phil Harvey

📖

Sergey

🐛 💻

Tom

💬 🐛 🤔

Tommy Leung

🧑‍🏫

digimbyte

📖

This project follows the all-contributors specification. Contributions of any kind are welcome!

Contributing

We encourage you to contribute to Colyseus! Please check out the Contributing guide for guidelines about how to proceed. Join us!

Everyone interacting in Colyseus and its sub-projects' codebases, issue trackers and chat rooms is expected to follow the code of conduct.

License

MIT

colyseus-unity-sdk's People

Contributors

allion-lahirup avatar bawahakim avatar bhavik66 avatar bkcetinkaya avatar burhanyilmaz avatar caioteixeira avatar chnkd avatar deniszykov avatar doorbash avatar dstrawberrygirl avatar endel avatar jimmydjabali avatar joselsdev avatar jushii avatar kodypeterson avatar ls-erik avatar mentaman avatar mikeskydev avatar mitchlucid avatar mobyjames avatar niklaswolf avatar rbatistajs avatar rnd256 avatar seismic-cbrooks avatar vidski avatar wenish avatar xaverix avatar xii55 avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

colyseus-unity-sdk's Issues

Create test suite

The test suite should cover:

  • DeltaContainer (#14)
  • Client
  • Room
  • Parsing complex MessagePack objects from the server
  • Arrays support in patches (#15)

Getting exception when trying to Join room

I am trying to run an example app, that just opens the connection to the server and joins a room. I am using the Chat server example, and created a small Unity app that connects.

Creating the Client works fine and I am getting the OnOpen event.

Then I am trying to join the room and I get the following 2 exceptions:
Error: An exception has occurred during an OnMessage event., System.InvalidOperationException: Cannot access child value on Newtonsoft.Json.Linq.JValue. at Newtonsoft.Json.Linq.JToken.get_Item (System.Object key) [0x00000] in <filename unknown>:0 at Colyseus.Patcher.Patch (Newtonsoft.Json.Linq.JToken& document, Newtonsoft.Json.Linq.JArray patches) [0x00000] in <filename unknown>:0 at Colyseus.Room.ApplyPatches (Newtonsoft.Json.Linq.JArray patches) [0x00000] in <filename unknown>:0 at Colyseus.Client.OnMessageHandler (System.Object sender, WebSocketSharp.MessageEventArgs e) [0x00000] in <filename unknown>:0 ...

And:
Error: An exception has occurred while receiving a message., WebSocketSharp.WebSocketException: The header part of a frame cannot be read from the data source. at WebSocketSharp.WebSocketFrame+<>c__DisplayClass7.<ReadAsync>b__6 (System.Byte[] header) [0x00000] in <filename unknown>:0 at WebSocketSharp.Ext+<>c__DisplayClass6.<ReadBytesAsync>b__5 (IAsyncResult ar) [0x00000] in <filename unknown>:0

My join code is pretty straight forward:
room = this.colyseus.Join ("chat_room");

I am using the binaries, and have not checked out from git, so maybe it's a problem that was fixed?

Client which creates the room gets NullReferenceException on Startup

On the client which creates a new room will have this NullReference:

NullReferenceException: Object reference not set to an instance of an object
Colyseus.Compare.Generate (GameDevWare.Serialization.IndexedDictionary`2 mirror, GameDevWare.Serialization.IndexedDictionary`2 obj, System.Collections.Generic.List`1 patches, System.Collections.Generic.List`1 path) (at Assets/Plugins/Colyseus/DeltaListener/Compare.cs:66)
Colyseus.Compare.GetPatchList (GameDevWare.Serialization.IndexedDictionary`2 tree1, GameDevWare.Serialization.IndexedDictionary`2 tree2) (at Assets/Plugins/Colyseus/DeltaListener/Compare.cs:26)
Colyseus.DeltaContainer.Set (GameDevWare.Serialization.IndexedDictionary`2 newData) (at Assets/Plugins/Colyseus/DeltaListener/DeltaContainer.cs:50)
Colyseus.Room.Patch (System.Byte[] delta) (at Assets/Plugins/Colyseus/Room.cs:177)
Colyseus.Room.ParseMessage (System.Byte[] recv) (at Assets/Plugins/Colyseus/Room.cs:163)
Colyseus.Room.Recv () (at Assets/Plugins/Colyseus/Room.cs:73)
Colyseus.Client.Recv () (at Assets/Plugins/Colyseus/Client.cs:90)
ColyseusClient+<Start>c__Iterator0.MoveNext () (at Assets/Scripts/Network/ColyseusClient.cs:55)
UnityEngine.SetupCoroutine.InvokeMoveNext (IEnumerator enumerator, IntPtr returnValueAddress) (at C:/buildslave/unity/build/Runtime/Export/Coroutines.cs:17)

I can open other clients, join the room and everything works fine for them.

any idea why this could happen?

its pretty much the Start function from the docs:
https://github.com/BroProducts/mem-client/blob/master/MemMapPrototype/Assets/Scripts/Network/ColyseusClient.cs#L55

The Example Project modified so it has the use case which triggers the error in it
i only added 2 lines in the "server/chat_room.js" file.
Line 11 and Line 19
colyseus-unity3d-master-null-reference.zip

BUG: After reconnect client state won't update to client

After reconnect client, if there is any state changes, the unity client room listener won't pick up any update on room state.
The reconnected client can send signal to server, but whatever server update on roomstate, the client won't receive any feedback. Anyone can help me?

Coroutine or thread

Hello, i the previous version (before 0.10) i met some performances issue due to socker reading in coroutine then i move this in thread with queue system to process events.
Do you think than the v0.10 serialization will resolve this coroutine perfomance issue ?

This property is deprecated

I opened the project using Unity 2017.2.0f3:

Assets/UnityTestTools/IntegrationTestsFramework/TestRunner/Editor/Batch.cs(71,29): error CS0619: UnityEngine.Application.isWebPlayer' is obsolete: This property is deprecated and will be removed in a future version of Unity, Webplayer support has been removed since Unity 5.4'

v0.10 : KeyNotFoundException: The given key was not present in the dictionary.

I receive a key not found at https://github.com/colyseus/colyseus-unity3d/blob/master/Assets/Plugins/Colyseus/Serializer/Schema/Schema.cs#L335

I added logs to this file :
Each fields created at https://github.com/colyseus/colyseus-unity3d/blob/master/Assets/Plugins/Colyseus/Serializer/Schema/Schema.cs#L295

And log 335 line too.

Schema try to get an index not listed in 275 lines logs.

Try to get index 50 in a schema with 23 fields detected in constructor.

Fields generated by last version of c# generator (original version)

Version :
colyseus : 0.10.2
schema : 0.4.9

OnDisconnected event

The client does not react in any way when the connection with the server is lost.

application paused issue onUpdate sync

Hi, I just trying your framework, and I found out if I minimize my game in android(press home button), onUpdateHandler will paused too. And then after I unpaused it(get back into the game), onUpdate will give me so many patches. And also my client will go into laggy condition(input became delayed until all previous patches applied). I think all the patches should become fast forward, so the player will catch up quite fast with the current time. Any suggestion about how to handle this issue?

Arrays are not fully supported in patches

The patch Operation "add" does not work for Arrays in the gamestate. Instead, every time a new item gets pushed into it, the Operation for the patch is "replace" and the value is the full Array itself.

I could investigate this a bit further and found the origin of the Problem:
https://github.com/gamestdio/colyseus-unity3d/blob/master/Assets/Colyseus/DeltaListener/Compare.cs#L46
the type of oldVal and newVal in such cases is NOT Dictionary, but Array. So for Arrays the condition is always false and the else-case gets done.

In the JS-Client, this Problem does not exist because typeof [] = 'object'.

chatRoom.state.Listen does not work as expected

the Unity Client debug is showing state changes with op: "add" and path: "players", but the OnChangeFallback instead of OnAddPlayer is getting invoked. why?

regarding this piece:

chatRoom.state.Listen("players", "add", this.OnAddPlayer);
...
chatRoom.state.Listen(this.OnChangeFallback);

I believe that the OnAddPlayer function is set up to be the action listener for op: "add" and segment: "players", so why instead of it the function OnChangeFallback is getting invoked?

Exception: copy extends past end of input

Reported by @quanglam68 in the Gitter channel:


hi, I still learning the unity client. testing the code given for exchanging information with 2 clients and the server works fine. ex: trace in one client : OnUpdateHandler: { "players" : { "SkkPLJeag" : { "x" : 520, "y" : 0 }, "HJrDLkxpx" : { "x" : 255, "y" : 0 } } }
but when i make the data bigger in the server, this.state.players[client.id] = { a:0, b: 0, d:0, x: 0, y: 0 }; I have an error in the client when it tries to apply the patch

Exception: copy extends past end of input
Fossil.Delta.Apply (System.Byte[] origin, System.Byte[] delta) (at Assets/Colyseus/FossilDelta/Delta.cs:187)
Colyseus.Room.ApplyPatch (System.Byte[] delta) (at Assets/Colyseus/Room.cs:129)
Colyseus.Client.ParseMessage (System.Byte[] recv) (at Assets/Colyseus/Client.cs:179)
Colyseus.Client.Recv () (at Assets/Colyseus/Client.cs:90)
ColyseusClient.FixedUpdate () (at Assets/Source/colyseus/ColyseusClient.cs:39)

My analysis is the pb appear at the call : this._previousState = Fossil.Delta.Apply (this._previousState, delta, out error);
seems that _previousState array size is too small. How can we set its size to it is bigger to match with the data set in the server

I Lost a day to understand and to change various things but I cannot find a solution / or even an quickfix

Any help is appreciated . Tks

possibility to cast the state to a specific data type

Currently, the only way to cast the state to a specific data type is by de-serializing it again in the OnUpdate action:

room.OnUpdate += OnRoomUpdate;

   private void OnRoomUpdate(object sender, RoomUpdateEventArgs update)
    {
            var outputStream = new System.IO.MemoryStream();
            MsgPack.Serialize(update.state, outputStream);
            outputStream.Position = 0;
            this.gameRoom = MsgPack.Deserialize<GameRoom>(outputStream);

It would be great if the client allows to provide a data-type when joining the room - and use it for de-serializing automatically - for example:

client.Join<GameRoom>("game_room");

(Thanks for proposing @derwish-pro)

Unity2018.3.x: The type or namespace name 'DynamicMethod' could not be found

So with the newest Unity Version it will not work anymore since 'DynamicMethod' isnt anymore in the namespace 'System.Reflection.Emit'

So the problem is in the GameDevWare.Serialization dependency

Assets\Plugins\GameDevWare.Serialization\Metadata\ReflectionUtils.cs(86,34): error CS0246: The type or namespace name 'DynamicMethod' could not be found (are you missing a using directive or an assembly reference?)
Assets\Plugins\GameDevWare.Serialization\Metadata\ReflectionUtils.cs(142,34): error CS0246: The type or namespace name 'DynamicMethod' could not be found (are you missing a using directive or an assembly reference?)

DeltaContainer not triggering a data change

@derwish-pro reported a problem in the DeltaContainer recently, with a patch: https://gist.github.com/derwish-pro/ecfd2c143b31816a408ef380e74ac21d

More info:

I have such a state of the game room on the server-side:

this.state.game.turn++;

I want to set a listener on the unity-side to catch this path. How can I do it?
I tried:

 room.Listen("game/turn", OnGameTurn);

and

  room.Listen("game/turn/:number", OnGameTurn);

None of the ways work.

I had to do a fix in DeltaContainer (unity side) to make it work.

Bad Checksum

When 5th client joins the server, then this error coming on client side.

Exception: bad checksum
Fossil.Delta.Apply (System.Byte[] origin, System.Byte[] delta) (at Assets/Plugins/FossilDelta/Delta.cs:204)
Colyseus.Room.Patch (System.Byte[] delta) (at Assets/Plugins/Colyseus/Room.cs:173)
Colyseus.Room.ParseMessage (System.Byte[] recv) (at Assets/Plugins/Colyseus/Room.cs:163)
Colyseus.Room.Recv () (at Assets/Plugins/Colyseus/Room.cs:73)
Colyseus.Client.Recv () (at Assets/Plugins/Colyseus/Client.cs:88)
ColyseusClient+<Start>c__Iterator0.MoveNext () (at Assets/ColyseusClient.cs:40)
UnityEngine.SetupCoroutine.InvokeMoveNext (IEnumerator enumerator, IntPtr returnValueAddress) (at C:/buildslave/unity/build/Runtime/Export/Coroutines.cs:17)

After this error, 5th client not getting any messages from server.

cannot .Listen to mutations on a string

(Reported by @aloani20 on gitter)

hi guys . I have this situation . on my client I was listening to property called "turn" using room.Listen ("turn", this.OnTurnChange); and the state on the server look like this

this.setState({
dice : 0 ,
turn : "none"
});

but when i mutate the value of dice i could see the change on the client but changing turn did not trigger this.OnTurnChange.

I have come up with a result that mutating javascript string variable on the server did not effect the room client listener.

InvalidCastException Room.cs

Hi , i have a new bug , its full random , i cant reproduce by my self
InvalidCastException: Cannot cast from source type to destination type. Colyseus.Room.ParseMessage (System.Byte[] recv) (at Assets/Plugins/Colyseus/Room.cs:153) Colyseus.Room.Recv () (at Assets/Plugins/Colyseus/Room.cs:83) Colyseus.Client.Recv () (at Assets/Plugins/Colyseus/Client.cs:90) WsHandler+<Start>c__Iterator1.MoveNext () (at Assets/Scripts/Network/Websockets/WsHandler.cs:144)
On Line 153 Room.cs :
this.sessionId = (string) message [1];

v0.10 : OnAdd with extended Schema

Hi, i have a class A who contains a MapSchema of classes B.

class A extends Schema {
    @type({ map: B}) children= new MapSchema<B>();
}

When i add an element in MapSchema OnAdd is triggered (normal behaviour)

If i extend B with a C class :

class C extends B {

}

OnAdd is triggered with B type instead of C.

Debug :

A.children.OnAdd += OnAddBClass;

public void OnAddBClass(object sender, KeyValueEventArgs<B, string> item)
	{
		// Always B type here, cannot access to C fields, invalid casting when try to cast B to C
	}

Notes : all classes are generated and heritance too, C is see as B by c# compilator

BUG: NullReferenceException: Object reference not set to an instance of an object

When I launch the project, I get an error: a connection in my room is null.

Logs from Unity:

ws://localhost:8080
UnityEngine.Debug:Log(Object)
c__Iterator0:MoveNext() (at Assets/ColyseusClient.cs:25)
UnityEngine.SetupCoroutine:InvokeMoveNext(IEnumerator, IntPtr)

Let's connect the client!
UnityEngine.Debug:Log(Object)
c__Iterator0:MoveNext() (at Assets/ColyseusClient.cs:30)
UnityEngine.SetupCoroutine:InvokeMoveNext(IEnumerator, IntPtr)

WebSocketSharp Open!
UnityEngine.Debug:Log(Object)
c__Iterator0:<>m__1(Object, EventArgs) (at Assets/Plugins/WebSocket/WebSocket.cs:237)
WebSocketSharp.Ext:Emit(EventHandler, Object, EventArgs)
WebSocketSharp.WebSocket:open()
WebSocketSharp.c__AnonStorey10:<>m__C(IAsyncResult)

Let's join the room!
UnityEngine.Debug:Log(Object)
c__Iterator0:MoveNext() (at Assets/ColyseusClient.cs:33)
UnityEngine.SetupCoroutine:InvokeMoveNext(IEnumerator, IntPtr)

Connected to server. Client id: hDwGaUNFF
UnityEngine.Debug:Log(Object)
ColyseusClient:OnOpenHandler(Object, EventArgs) (at Assets/ColyseusClient.cs:68)
Colyseus.Client:ParseMessage(Byte[]) (at Assets/Plugins/Colyseus/Client.cs:191)
Colyseus.Client:Recv() (at Assets/Plugins/Colyseus/Client.cs:84)
c__Iterator0:MoveNext() (at Assets/ColyseusClient.cs:54)
UnityEngine.SetupCoroutine:InvokeMoveNext(IEnumerator, IntPtr)

NullReferenceException: Object reference not set to an instance of an object
Colyseus.Room.Send (System.Object data) (at Assets/Plugins/Colyseus/Room.cs:144)
ColyseusClient+c__Iterator0.MoveNext () (at Assets/ColyseusClient.cs:59)
UnityEngine.SetupCoroutine.InvokeMoveNext (IEnumerator enumerator, IntPtr returnValueAddress) (at C:/buildslave/unity/build/Runtime/Export/Coroutines.cs:17)

Logs from Server:

[nodemon] 1.12.1
[nodemon] to restart at any time, enter rs
[nodemon] watching: .
[nodemon] starting node --harmony ./index.js
Running on ws://localhost:8080
TypeError: Generator is already running
at next (native)
at fulfilled (d:\Ouroborus\colyseus\colyseus-unity3d-master\Server\node_modules\colyseus\lib\MatchMaker.js:4:58)
at process._tickCallback (internal/process/next_tick.js:103:7)

Unity 2018.2.12f1. Windows 10.

v0.10 : Strange behaviour in nested Schemas

Hi, i using 3 level nested structure :
Player --> Camp --> Position
Where camp is just a name/position
and Position is a vector of 3 floats

At the first player connection, all works fine.
But if i leave the room (it disposed : normal behaviour), and join a new one roomthen camp position is wrong (0,0,0).

If a restart the server, the first connection give me the good one camp position, and others connections send me a camp with 0,0,0 vector.

Note : i do not use any cache system.
All room state recreated from scratch

Error: ["op"] does not seem to exist in the JArray

As reported by Chris Dillman:

Could you try running your unity test code under Unity 5.40f3 or around there the non beta version of unity.

Im getting an exception in

Where ["op"] does not seem to exist in the JArray.


public void Patch (ref JToken document, JArray patches) 

    string operation = patches [i]["op"].ToString(); 

and this is leading the client closing the connection.
This is immediately after successfully joining a room.

Bug Report - Client.cs + Suggestion fix

Hi, I discovered today a bug apparently already mentioned on other forum but no solution was found.
https://discuss.colyseus.io/assets/uploads/files/1534256094505-21a5ff34-cf8b-468e-b6ef-97ed2d4a3220-image-resized.png
Colyseus/Client.cs : 88
https://discuss.colyseus.io/assets/uploads/files/1534256263835-6696875e-5ce8-4c5f-ac67-3b12d5515e82-image.png
I made some changes, and I have no problem, no more bug, could you validate this code and integrate it into the original code
https://discuss.colyseus.io/assets/uploads/files/1534256393568-6e68405f-5811-410d-bb09-357b7d14a7bf-image.png
Thanks

Unity client doenst work without loop part

The unity client can create and join the lobby if i don't use the sample part below.
Is this code piece really necessary to use the client?
`int i = 0;

	while (true)
	{
		client.Recv();

		i++;

		if (i % 50 == 0) {
			room.Send("some_command");
		}

		yield return 0;
	}`

Does not work on IOS

Hello it works fine on the Editor. But when the Game is Running on a IOS Device (iPhone 5) it is not working. I get the following Debug log form xCode.

WARNING: Shader Unsupported: 'Nature/Terrain/Specular' - Pass 'FORWARD' has no vertex shader
WARNING: Shader Unsupported: 'Nature/Terrain/Specular' - Pass 'FORWARD' has no vertex shader
WARNING: Shader Unsupported: 'Nature/Terrain/Specular' - Pass 'PREPASS' has no vertex shader
WARNING: Shader Unsupported: 'Nature/Terrain/Specular' - Pass 'PREPASS' has no vertex shader
WARNING: Shader Unsupported: 'Nature/Terrain/Specular' - Pass 'META' has no vertex shader
WARNING: Shader Unsupported: 'Nature/Terrain/Specular' - All passes removed
UnloadTime: 18.202501 ms
Application Start
UnityEngine.DebugLogHandler:Internal_Log(LogType, String, Object)
UnityEngine.DebugLogHandler:LogFormat(LogType, Object, String, Object[])
UnityEngine.Logger:Log(LogType, Object, Object)
UnityEngine.Logger:Log(LogType, Object)
System.Text.RegularExpressions.Syntax.ExpressionCollection:OnValidate(Object)
UnityEngine.Debug:Log(Object)
GameSession:Start()
 
(Filename: /Users/builduser/buildslave/unity/build/artifacts/generated/common/runtime/DebugBindings.gen.cpp Line: 51)

09/17/2017 16:31:37|Fatal|WebSocket.acceptException|System.Net.Sockets.SocketException: Connection refused
                            at Colyseus.Client.Join (System.String roomName, System.Collections.Generic.Dictionary`2 options) [0x00000] in <filename unknown>:0 
                            at System.Net.Sockets.Socket.Connect (System.Net.EndPoint remoteEP, Boolean requireSocketPolicy) [0x00000] in <filename unknown>:0 
                            at System.Net.Sockets.Socket.Connect (System.Net.EndPoint remoteEP) [0x00000] in <filename unknown>:0 
                            at System.Net.Sockets.TcpClient.Connect (System.Net.IPEndPoint remote_end_point) [0x00000] in <filename unknown>:0 
                            at System.Net.Sockets.TcpClient.Connect (System.Net.IPAddress[] ipAddresses, Int32 port) [0x00000] in <filename unknown>:0 
                            at System.Net.Sockets.TcpClient.Connect (System.String hostname, Int32 port) [0x00000] in <filename unknown>:0 
                            at System.Net.Sockets.TcpClient..ctor (System.String hostname, Int32 port) [0x00000] in <filename unknown>:0 
                            at WebSocketSharp.WebSocket.setClientStream () [0x00000] in <filename unknown>:0 
                            at WebSocketSharp.WebSocket.doHandshake () [0x00000] in <filename unknown>:0 
                            at WebSocketSharp.WebSocket.connect () [0x00000] in <filename unknown>:0 
09/17/2017 16:31:37|Fatal|WebSocket.acceptException|System.Net.Sockets.SocketException: Connection refused
                            at Colyseus.Client.Join (System.String roomName, System.Collections.Generic.Dictionary`2 options) [0x00000] in <filename unknown>:0 
                            at System.Net.Sockets.Socket.Connect (System.Net.EndPoint remoteEP, Boolean requireSocketPolicy) [0x00000] in <filename unknown>:0 
                            at System.Net.Sockets.Socket.Connect (System.Net.EndPoint remoteEP) [0x00000] in <filename unknown>:0 
                            at System.Net.Sockets.TcpClient.Connect (System.Net.IPEndPoint remote_end_point) [0x00000] in <filename unknown>:0 
                            at System.Net.Sockets.TcpClient.Connect (System.Net.IPAddress[] ipAddresses, Int32 port) [0x00000] in <filename unknown>:0 
                            at System.Net.Sockets.TcpClient.Connect (System.String hostname, Int32 port) [0x00000] in <filename unknown>:0 
                            at System.Net.Sockets.TcpClient..ctor (System.String hostname, Int32 port) [0x00000] in <filename unknown>:0 
                            at WebSocketSharp.WebSocket.setClientStream () [0x00000] in <filename unknown>:0 
                            at WebSocketSharp.WebSocket.doHandshake () [0x00000] in <filename unknown>:0 
                            at WebSocketSharp.WebSocket.connect () [0x00000] in <filename unknown>:0 
Error: An exception has occurred while connecting.
UnityEngine.DebugLogHandler:Internal_Log(LogType, String, Object)
UnityEngine.DebugLogHandler:LogFormat(LogType, Object, String, Object[])
UnityEngine.Logger:Log(LogType, Object, Object)
UnityEngine.Logger:Log(LogType, Object)
System.Text.RegularExpressions.Syntax.ExpressionCollection:OnValidate(Object)
UnityEngine.Debug:LogError(Object)
<Start>c__Iterator0:MoveNext()
Colyseus.Connection:_OnOpen(Object, EventArgs)
UnityEngine.SetupCoroutine:InvokeMoveNext(IEnumerator, IntPtr)
 
(Filename: /Users/builduser/buildslave/unity/build/artifacts/generated/common/runtime/DebugBindings.gen.cpp Line: 51)

09/17/2017 16:31:38|Error|WebSocket.Close|The WebSocket connection has already been closed.
Error: An exception has occurred while connecting.
UnityEngine.DebugLogHandler:Internal_Log(LogType, String, Object)
UnityEngine.DebugLogHandler:LogFormat(LogType, Object, String, Object[])
UnityEngine.Logger:Log(LogType, Object, Object)
UnityEngine.Logger:Log(LogType, Object)
System.Text.RegularExpressions.Syntax.ExpressionCollection:OnValidate(Object)
UnityEngine.Debug:LogError(Object)
<Start>c__Iterator0:MoveNext()
Colyseus.Connection:_OnOpen(Object, EventArgs)
UnityEngine.SetupCoroutine:InvokeMoveNext(IEnumerator, IntPtr)
 
(Filename: /Users/builduser/buildslave/unity/build/artifacts/generated/common/runtime/DebugBindings.gen.cpp Line: 51)

09/17/2017 16:31:38|Error|WebSocket.Close|The WebSocket connection has already been closed.

Negative Numbers which client receives dont get parsed correctly

If i set a position of a Player in the server state to this:

currentPosition: {
  x: -30,
  y: 2.02,
  z: 0
}

on the client its this:

currentPosition: {
  x: 2,
  y: 2.02,
  z: 0
}

Client Side Code which prints out x wrong.
in debug u see its in DataChange already false

void OnPlayerChange (DataChange change)
{
	Debug.Log ("OnPlayerChange");
	Debug.Log (change.operation);
	Debug.Log (change.path["id"]);
	Debug.Log (change.value);

	var data = (IndexedDictionary<string, object>) change.value;

	var currentPosition = (IndexedDictionary<string, object>) data["currentPosition"];

	var x = Convert.ToSingle (currentPosition ["x"]); //prints out 2 but should be -30
	var y = Convert.ToSingle (currentPosition ["y"]);
	var z = Convert.ToSingle (currentPosition ["z"]);
}

Modified Version of the Unity client example which set the spawn of the cube to this
addplayer

modified client so he sets also the Z:
grabvalue

actual spawn: (ignore X because its already moved by script)
spawn

colyseus-unity3d-master-wrong-parsing.zip

Unity ECS Support/Example

Unity will bring ECS this year and some stuff is already out.
I think Colyseus would work really great with the unity ECS.
I opened this issue to bring it up.

Maybe i would already be enough to just change the ColyseusClient example.

GetAvailableRooms doesn't deserialise metadata correctly

When I set my room metadata, even at Client.cs:220 you can see that metadata is null in the received object.

  onInit(options: any): void {
    this.setState(this.initialPlayerState());
    this.maxClients = options.maxClients || MAX_PLAYERS_IN_ROOM;
    this.setMetadata({
      mode: options.mode || '',
      name: options.name || `Room ${this.roomId}`,
    });
  }

I tried JSON.stringifying the metadata object, still don't get a string on the client side.

onClose

onClose event dose not work !

Don't work GetAvailableRooms

Hi!!!
Why in Client.cs commented code part with function GetAvailableRooms?
When that will be fixed and i can work with that?

//		public void GetAvailableRooms (string roomName, Action<RoomAvailable[]> callback)
//		{
//			int requestId = ++this.requestId;
//			this.connection.Send (new object[]{Protocol.ROOM_LIST, requestId, roomName});
//
//			this.roomsAvailableRequests.Add (requestId, callback);
//
//			// // USAGE
//			// this.client.GetAvailableRooms ("chat", (RoomAvailable[] obj) => {
//			// 	for (int i = 0; i < obj.Length; i++) {
//			// 		Debug.Log (obj [i].roomId);
//			// 		Debug.Log (obj [i].clients);
//			// 		Debug.Log (obj [i].maxClients);
//			// 		Debug.Log (obj [i].metadata);
//			// 	}
//			});
//		}

Room is not disposed after all clients disconnect

The problem is that the room does not dispose even after all of the clients leave. Then if another player searches for room to join he gets connected to this room with the "ghost" client.

The room gets finally disposed only after the game is re-launched by the client who initially created the room. Weird.

This happens only if the clients leave by instantly closing the application.

void OnApplicationQuit()
{
    // Ensure the connection with server is closed immediatelly
    LeaveRoom();
    if (Colyseus != null) Colyseus.Close();
}

public void LeaveRoom()
{
    if (Room != null)
    {
        Room.Leave(true);
    }
}

void OnRoomLeft(object sender, EventArgs e)
{
    Room = null;
}

v0.10 : c# file generation and extends

Hi, i have a class A extending schema and another class B extending the A at generation fields with @type decorator in A are not present in class B, and c# class B extends schema and not class A.
Any solution for this ?

Thank you.

OnPlayerMove example?

Hi there! I have just discovered Colyseus and I'm trying to use it in a simple Unity game just to see how it feels. I am having trouble understanding how to trigger OnPlayerMove. I tried something like this in Unity:

string[] coordsX = {"x", transform.position.x.ToString() };
chatRoom.Send(coordsX);

but it doesn't seem to do anything. Can you give me a small example on how to do this? Thank you!

data which u reciev over onData is private

If u add a listner to onData u dont get the data

room.OnData += (object sender, MessageEventArgs e) => Debug.Log(e.data);

The data is private and so u cant accessible
ondataisprivate

Windows UWP-Support

Hi, I want to use colyseus in a project where I have to write a Unity Windows UWP App. When I wanted to build the project, I got an error message because the WebSocket implementation doesn't work on UWP.
Now I thought I could add another preprocessor-directive in WebSocket.cs and write the needed functions with a WebSocket implementation for UWP (https://docs.microsoft.com/en-us/windows/uwp/networking/websockets).

I just wanted to make sure, which functions I have to write for this. I'm thinking, it's

Send()
Recv()
Connect()
Close()

am I right?

v 0.10 : Nested schemas

Hi, i tried to externalize X and Y in unity exemple, in a Position schema and look for changes in this new Schema and X increment in JS onMessage method.
I regenerated the c# classes, change the code accordly and register an handler on the position in OnPlayerAdd method like this :

item.Value.position.OnChange += OnPositionChange;

I do not receive any event from position change. Server debug changes on Position.

Here the source code.

colyseus-unity3d.zip

Thank you for your help.

KeyNotFoundException: The given key was not present in the dictionary.

Hi,

I might not be using the right terms to describe what I want to achieve but please bear with me on the following description:

This is from he example code ColyseusClient.cs

room.Listen ("players/:id/:axis", this.OnPlayerMove);
room.Listen ("players/:id", this.OnPlayerChange);
room.Listen ("messages/:number", this.OnMessageAdded);
room.Listen("test_messages/:odd_numbers", this.OnMessageAdded);

Where do I check to find the key axis this set in players object?
Where do I check to find the key number for messages?

How do I add new keys?
For example,
constructor () {
super();

this.setState({
  players: {},
  messages: [],
  test_messages: []
});

}

In test_messages I would like a key to be name "odd_numbers" instead of numbers, how to change it? Or documentation explaining this would help.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.