Git Product home page Git Product logo

unitysocketio's Introduction

UnitySocketIO

The project is the socket.io client for unity3d, written in C#. It's based on socketio4net.Client (http://socketio4net.codeplex.com/). However, socketio4net.Client only provides a .NET 4.0 C# client, and does compatible with unity3d. We've done a lot of works on supporting unity3d.

The project was initially designed for unity client of pomelo framework, which is a powerful, scalable game server framework.

How to use

It is very simple to use UnitySocketIO. Copy all the DLLS locating in the file of /bin/Debug/ to your project.

Of course, you can download this project and compile it:

git clone https://github.com/NetEase/UnitySocketIO.git

API

Create and initialize a new UnitySocketIO client.

Client client = new Client(url);

client.Opened += SocketOpened;
client.Message += SocketMessage;
client.SocketConnectionClosed += SocketConnectionClosed;
client.Error +=SocketError;

client.Connect();

private void SocketOpened(object sender, MessageEventArgs e) {
    //invoke when socket opened
}

Send message to server.

client.Send(messge);

Get message from server.

private void SocketMessage (object sender, MessageEventArgs e) {
    if ( e!= null && e.Message.Event == "message") {
        string msg = e.Message.MessageText;
       process(msg);
    }
}

Close connection.

client.Close();

##License (The MIT License)

Copyright (c) 2012-2013 NetEase, Inc. and other contributors

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the 'Software'), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

unitysocketio's People

Contributors

halfblood369 avatar sagivo avatar squaretone 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  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

unitysocketio's Issues

Unity Web Player

Hi,

You cann't build a Unity3d Web Player Release, the reason for this is the Security Sand Box of the Web Player (see http://docs.unity3d.com/Manual/SecuritySandbox.html).

The following error message appears when you try to build your Unity3d project on the Web Player Platform:
ArgumentException: The Assembly System.Runtime.Serialization is referenced by SimpleJson. But the dll is not allowed to be included or could not be found....
SimpleJson is using Reflections these won't be supported by the Web Player Subset.

At the moment I'm trying to replace the SimpleJson.dll with the SimpleJSON from the Unify Community (http://wiki.unity3d.com/index.php/SimpleJSON). Maybe someone of you could give me some feedback to this decision and/or maybe someone comes up with an other idea.

Best Regards

Flo

Can't do it.

I ended it up with error bug. Don't know exactly how to use. Sorry if can, please anyone leave me a small project. Thanks!

Hi

i have problem to use this.

when i try to emit to server, sometimes it's not call callback func.
( only application. test in editor, server send message ordinarily(pc))

why is that ?

Unitysocketio在unity3d中需要使用多线程吗?

服务器端使用Nodejs,前端使用unity3d,界面使用NGUI,通信用的unitysocketio,当我接收到服务器端返回的信息时,需要更新页面数据,但是报错了

TrySetSetString can only be called from the main thread.
Constructors and field initializers will be executed from the loading thread when loading a scene.
Don't use this function in the constructor or field initializers, instead move initialization code to the Awake or Start function.

向大家请教如何处理这个问题,是否是线程的问题还是其它的?

Too high processor usage

I narrowed down the problem to the thread using dequeuOutboundMessages. It eats more than 100% of a cpu core. Just this thread alone connected to a Node.js server which sends a message once in a while. Once a minute or less.

Not working with new socket.io 1.0.4 server

Hi there,

I've been playing with new socket.io 1.0.4 server side, but the current UnitySocketIO client cannot connect. It did work properly with version 0.9 of socket.io server.

Please consider to upgrade UnitySocketIO client to compatible with new socket io 1.x.

Many thanks

Server Part

Hi Everyone,
I am working on video stream of a camera of a device in unity, here everything is give for how to start client can any give me hint how to start the server where this client send and receive data.
I am beginner in the this fields . So looking for your help.
Thanks in advance.

8 hours straight trying to make the simplest thing work

Hi,

I created a socket io server like this:

var io = require('socket.io').listen(5000);

io.sockets.on('connection', function (socket)
{
io.sockets.emit('evt', { foo: 'bar'});
});

and a pomelo client like this

using UnityEngine;
using System;
using System.Collections;
using SimpleJson;
using pomeloUnityClient;

public class TargetController : MonoBehaviour
{
private PomeloClient pclient = null;

void Start()
{
    string url = "http://localhost:5000";
    pclient = new PomeloClient(url);
    pclient.init();

    pclient.On("evt", (data)=>{
        Debug.Log("received something");
    });

    JsonObject emptyMessage = new JsonObject();
    emptyMessage.Add ("foo", "bar");

    pclient.notify("connection", emptyMessage);
}

}

and when I run the client part the server side logs this:

debug - client authorized
info - handshake authorized BPbGYLLp1TfVeVOaKZAD

And on unity client part I get nothing, zero, no error, warnings, logs, nothing.

Can you help me find out what is missing?

Ty,

not able to send on iOS

We're stuck with a serious issue on iOS in that it is not able to send messages to a server (running node.js with socket.io). It receives without problems, and the very same code works for other platforms (both sending and receiving).

Anyone out there who can help with this would be highly appreciated.

Socket connection issue in carrier network

we are using this plugin for multiplayer game and from last 3 days we found socket connection issue in Reliance JIO carrier in India
i am doing socket connection but socket is not connected to that server for JIO carrier rest carrier it works fine
so can you please help out for same to resolve
as we have try to connect with socket io version 2 and version 3 both
but not works

awaiting for response

Thanks

Source for SimpleJSON/ version number of SimpleJson being used

Hi,
I have been looking for the source code of the SimlpeJSON.dll over the internet , but the project seems to have updated as the latest project on http://simplejson.codeplex.com/ has namespace as Simple.Json, where as the one that has been in this project has namespace SimpleJson.SimpleJson.
Can you share the source of the dll that is used in this project ?

Thanks
Neerav
EDIT: I am new to GitHub , hence do not know how to post a question, please feel free to change it accodingly.

Error compiling

Hello, using M.VC#2010 Express the compiler drops an error with a duplicate dll function reference:

Error   49  The type 'System.Collections.Concurrent.ConcurrentQueue<T>' exists in both 'C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\.NETFramework\v4.0\mscorlib.dll' and 'C:\Games\Unity\UnitySocketIO-master\SocketIO\bin\Debug\SuperSocket.ClientEngine.Core.dll' C:\Games\Unity\UnitySocketIO-master\SocketIO\socketio\Client.cs 24  11  SocketIO

any idea how to fix this?

error initializing handshake for secure connection

when i tried to connect to secure https server "error initializing handshake" connection is given. The server administrator gave the following as javascript method to connect

socket = io.connect('https://abcd.com:321010', {secure: true});

but the in socketio the client constructor takes only one argument, the url.How can we pass this second parameter while connecting? or in general how to connect with secure server??

thanks in advance

XHR-Polling support?

When running socket in long polling mode, eg:

sio.configure(function() {
sio.set("transports", ["xhr-polling"]);
sio.set("polling duration", 10);
});

I get the following socket debug message, and none of the messages are received by Unity:

info - handshake authorized WOsMURlFxbhuWDH0Ac0c
warn - unknown transport: "websocket"

Is this a matter of changing the UnitySocketIO settings, or is xhr-polling currently not supported?

使用UnitySocketio打包后连接不上服务器,pomelo-unitychat可以聊天

客户端使用的是UnitySocketio与服务器进行通信,与pomelo-unitychat (https://github.com/NetEase/pomelo-unitychat) 一样是基于U3D与NodeJS的项目。
但是服务器端没有用Pomelo,只是单纯的Nodejs,客户端使用UnistySocketIO。
在Unity中开发是能够正常与服务器连接,接收数据,但是打包之后就连接不上服务器。打包成什么格式都不能连接服务器。经过几次尝试之后,我很认真地参考了pomelo-unitychat,就是socket那部分,pomelo-unitychat使用PomeloClient,我的项目使用的是UnitySocketIO。
我把pomelo-unitychat运行起来的效果如下:
chat
我做了一个测试Demo和我的项目写法是一样的,地址如下:
百度网盘:
只有源码:http://pan.baidu.com/share/link?shareid=473125&uk=1276168936
带打包文件:http://pan.baidu.com/share/link?shareid=473126&uk=1276168936
新浪V盘:
http://vdisk.weibo.com/s/y4_1P

Problems connecting to socket.io

Hi. I'm writing a project in Unity4 and I'd love to use your great library to connect with a socket.io server but I'm running into some problems.

In Javascript I would usually write something like:

var socket = io.connect(url);
socket.emit(my_event, {my : 'data'} );

In C# (In Unity/MonoDevelop) I'm writing something like:

socket = new Client(url);
socket.Connect();
socket.Send(???)

Problems:

  1. I'm getting lots of non-descript errors in the console on connection even though it tells me it has connected (I'm doing a Console.log(e.Message))
    socket error: SocketIOClient.Messages.EventMessage
    socket opened
    socket error: SocketIOClient.Messages.ConnectMessage
    (note: this also seems to keep retrying in the background even after I stop running the Unity game, and sometimes ends in a freeze/crash)
  2. I have no idea how to send the (my_event, {my : 'data'} ) combination to socket.io as the 'Send' method of the Client class only takes a single argument. Do I need to join the two arguments as a single piece of JSON somehow?

Thanks for any help you can share - it would be super appreciated!
(or any examples would be great?)

Thanks (and congratulations!)
Phil

iOS运行时出错

大家好,我遇到的问题是这样的:

客户端采用Unity3D,并利用UnitySocketIO和Node.js服务器通讯。在Unity3D编辑器中测试一切都正常,但编译为iOS版本后,发现可以建立连接,却无法发送消息。错误信息如下:

ArgumentOutOfRangeException: Argument is out of range.
Parameter name: options
at System.Text.RegularExpressions.Regex.validate_options (RegexOptions options) [0x00000] in :0
at System.Text.RegularExpressions.Regex..ctor (System.String pattern, RegexOptions options) [0x00000] in :0
at SocketIOClient.Messages.Message..cctor () [0x00000] in :0
Rethrow as TypeInitializationException: An exception was thrown by the type initializer for SocketIOClient.Messages.Message
at SocketIOClient.Client.wsClient_OpenEvent (System.Object sender, System.EventArgs e) [0x00000] in :0
at WebSocket4Net.WebSocket.OnHandshaked () [0x00000] in :0
at WebSocket4Net.Command.Handshake.ExecuteCommand (WebSocket4Net.WebSocket session, WebSocket4Net.WebSocketCommandInfo commandInfo) [0x00000] in :0
at WebSocket4Net.WebSocket.ExecuteCommand (WebSocket4Net.WebSocketCommandInfo commandInfo) [0x00000] in :0
at WebSocket4Net.WebSocket.OnDataReceived (System.Byte[] data, Int32 offset, Int32 length) [0x00000] in :0
at WebSocket4Net.WebSocket.client_DataReceived (System.Object sender, SuperSocket.ClientEngine.DataEventArgs e) [0x00000] in :0
at SuperSocket.ClientEngine.ClientSession.OnDataReceived (System.Byte[] data, Int32 offset, Int32 length) [0x00000] in :0
at SuperSocket.ClientEngine.AsyncTcpSession.ProcessReceive (System.Net.Sockets.SocketAsyncEventArgs e) [0x00000] in :0
at SuperSocket.ClientEngine.AsyncTcpSession.SocketEventArgsCompleted (System.Object sender, System.Net.Sockets.SocketAsyncEventArgs e) [0x00000] in :0
at System.Net.Sockets.SocketAsyncEventArgs.OnCompleted (System.Net.Sockets.SocketAsyncEventArgs e) [0x00000] in :0
at System.Net.Sockets.SocketAsyncEventArgs.ReceiveCallback () [0x00000] in :0

恳请大家的帮助,谢谢

On windows I can't connect to url with host names.

It seems that I can connect only to URLs containing IP addresses. It does handshaking successfully but after that just waits in "connecting" state forever.

For example if I try to connect ro 127.0.0.1:3700 it works, localhost:3700 doesn't.
Tried to connect to a remote server by host name — doesn't work.

Works fine on OS X.

Error initializing handshake with local url.

When I tried create a new socket by doing same as how API done,It cames:
Here is my code ,just same as api:https://github.com/NetEase/UnitySocketIO

void Start () {
    string url = "http://192.168.199.128:5500";
    client = new Client(url);
    client.Opened += SocketOpened;
    client.Message += SocketMessage;
    client.SocketConnectionClosed += SocketConnectionClosed;
    client.Error += SocketError;
    client.Connect();
}

private void SocketError(object sender, ErrorEventArgs e)
{
    Debug.Log(e.Message);
}

private void SocketConnectionClosed(object sender, EventArgs e)
{
    Debug.Log(e);
}

private void SocketMessage(object sender, MessageEventArgs e)
{
    Debug.Log(e.Message);
}

private void SocketOpened(object sender, EventArgs e)
{
    Debug.Log("Socket Connected!");
}

My Server is running at a VMWare machine.
image
And the Unity print:
image

Could you help?Thanks!

Cross platform?

Is this library cross platform? Will it work with Unity3D running on OSX? Thanks

What version of socket.io do I need?

I am struggling to get this working, I only received "handshake authorized" in my server, and socket opened event does not fire.

Server:

io.sockets.on('connection', function(socket) {
    console.log("-- Socket connected!");
    socket.emit("message", "Welcome fagget!");
});

Unity client:

        client = new Client("http://localhost:1337");
        client.Opened += SocketOpened;
        client.Message += SocketMessage;
        client.SocketConnectionClosed += SocketConnectionClosed;
        client.Error += SocketError;

        Debug.Log("Client set up, connecting..");

        client.On("message", data =>
        {
            Debug.Log("Message received!");                         
        });

        client.Connect();

Could I use for mobile

i see you mention net 4.0 in your introduction.Since Unity3d use net2.0 build android, so i wonder it works for mobile platform?
forgive me, my english is not very good.

Emit fixed, but DLL's not updated

Hey there!

Thanks for making this interesting library. I've noticed you solved the "emit" problem, but the libraries have not been rebuilt. It worked just fine when I re-built them, but the current "bin/debug" is outdated.

Just putting this here in case anybody still has issues with emit. If someone can update the repo, that would probably help a few users (The ones who don't feel comfortable building them) with their problems.

Thanks!
(I'd update them myself but I figure one of the authors doing it is faster than a pull request.)

Cant emit SocketIO Events

I cant seem to emit Events on my SocketIO node-js server. The Emit function doesnt seem to do anything.

I have seen some examples from pomelo clients but they use a custom protocol which SocketIO Servers dont recognize...So why is this called a SocketIO library ? Its a Websocket library using a custom protocol imo.

I can recieve Events in Unity with my own custom EventHandler, but i cant send Messages to the server.

Any help appreciated, the pomelo examples dont help me though, its a custom binary protocol.

Error with Example code! Help!

Here is my code

using UnityEngine;
using SimpleJson;
using SuperSocket;
using WebSocket4Net;
using SocketIOClient;


public class test : MonoBehaviour{

    // Use this for initialization

    Client client = new Client("http://localhost:3998");

    void Start () {
        client.Opened += SocketOpened;
        client.Connect();
    }

    void SocketOpened(object sender, MessageEventArgs e){
        Debug.Log("connected");
    }

    // Update is called once per frame
    void Update () {

    }
}

This is my Error:

http://i.imgur.com/9NIwqhz.png

Message Event is null

I was following 'How to use' :

private void SocketMessage (object sender, MessageEventArgs e) {
if ( e!= null && e.Message.Event == "message") {
string msg = e.Message.MessageText;
process(msg);
}
}

But e.Message.Event is Null except if we use socket.send(string) on server.

socket.emit('loveall',{love:'emitting love'}) on server side gives null and not 'loveall' as event.

I am aware of the event handling from other issue posts, is this connected to that?
without this i need to parse the whole messagetext to get the event name.Please help
if i am doing any wrong.

Do you know any v3 or higher server?

Hello sir, I am an jr.Android Developer and created a socket.io client side with java. So I think you know there is v1 or v2 in client side for java. My problem is that my company use v3 in server side so I have to use v2 client (highest version in java) but I cant connect to their server. So I need to a v3 or higher server side url for test my client side for check the problem is in my side or in server side. Do you know any v3 or higher server?

Note: When I switch to v1 in client I can easly connect to other v2 servers.

Complete incompatibility with new Socket.IO

Unless i'm interpreting the example wrong, I have:

"void Start () {
MyClient = new Client("http://95.232.201.42:35352"); //Custom Port
MyClient.Message += SocketMessage;
MyClient.Opened += SocketOpened;
MyClient.SocketConnectionClosed += SocketConnectionClosed;
MyClient.Error += SocketError;

    MyClient.Connect();
}

"

The socket server doesn't detect the connection, and I know it works because I've had it work with other utilities.
Either i'm not giving the correct URi/URL or this is too outdated.

Don't work

///

    /// <para>Asynchronously calls the action delegate on event message notification</para>
    /// <para>Mimicks the Socket.IO client 'socket.on('name',function(data){});' pattern</para>
    /// <para>Reserved socket.io event names available: connect, disconnect, open, close, error, retry, reconnect  </para>
    /// </summary>


    /// <param name="eventName"></param>
    /// <param name="action"></param>
    /// <example>
    /// client.On("testme", (data) =>
    ///    {
    ///        Debug.WriteLine(data.ToJson());
    ///    });
    /// </example>
    public virtual void On(
        string eventName,
        Action<IMessage> action)
    {
        this.registrationManager.AddOnEvent(eventName, action);
    }

Callbacks cannot operate since not on Main Thread

Good evening, I've tried to use the library and I am able to output the message and parse it but if I want to operate on GameObjects. Unity won't let me because the callback function is not operation from the main thread.
Has anyone found a solution?
Cheers,
Roger

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.