示例#1
0
    void ConnectionStateChangedCallback(Message <NetworkingPeer> msg)
    {
        Debug.LogFormat("P2P {0} Connection state changed to {1}", msg.Data.ID, msg.Data.State);

        if (m_remotePlayers.ContainsKey(msg.Data.ID))
        {
            m_remotePlayers[msg.Data.ID].state = msg.Data.State;

            switch (msg.Data.State)
            {
            case PeerConnectionState.Connected:
                if (PlatformManager.MyID < msg.Data.ID)
                {
                    SendTimeSyncMessage(msg.Data.ID);
                }
                break;

            case PeerConnectionState.Timeout:
                if (PlatformManager.MyID < msg.Data.ID)
                {
                    Net.Connect(msg.Data.ID);
                }
                break;

            case PeerConnectionState.Closed:
                m_remotePlayers.Remove(msg.Data.ID);
                break;
            }
        }
    }
示例#2
0
        public string Send(string msg)
        {
            var text = "Not Ready";

            if (IsReady)
            {
                if (!IsConnected)
                {
                    Net.Connect(IpAddress, 8080);
                }

                var stream = Net.GetStream();
                var bytes  = Encoding.UTF8.GetBytes(msg);
                stream.Write(bytes, 0, msg.Length);

                while (Net.Available == 0)
                {
                    Thread.Sleep(10);
                }

                var len  = Net.Available;
                var read = new byte[len];
                stream.Read(read, 0, len);
                text = Encoding.UTF8.GetString(read);
                Console.WriteLine(text);
            }
            return(text);
        }
示例#3
0
    static int Connect(IntPtr L)
    {
        try
        {
            ToLua.CheckArgsCount(L, 4);
            Net           obj       = (Net)ToLua.CheckObject(L, 1, typeof(Net));
            string        arg0      = ToLua.CheckString(L, 2);
            int           arg1      = (int)LuaDLL.luaL_checknumber(L, 3);
            System.Action arg2      = null;
            LuaTypes      funcType4 = LuaDLL.lua_type(L, 4);

            if (funcType4 != LuaTypes.LUA_TFUNCTION)
            {
                arg2 = (System.Action)ToLua.CheckObject(L, 4, typeof(System.Action));
            }
            else
            {
                LuaFunction func = ToLua.ToLuaFunction(L, 4);
                arg2 = DelegateFactory.CreateDelegate(typeof(System.Action), func) as System.Action;
            }

            obj.Connect(arg0, arg1, arg2);
            return(0);
        }
        catch (Exception e)
        {
            return(LuaDLL.toluaL_exception(L, e));
        }
    }
示例#4
0
        public Task <INetPeer> Connect(IPEndPoint endPoint)
        {
            //check if we are already connected to this endpoint
            foreach (var pair in PeersByNetId)
            {
                if (endPoint.Equals(pair.Value.Channel.EndPoint))
                {
                    return(Task.FromResult((INetPeer)pair.Value));
                }
            }

            return(_pendingConnections.AddOrUpdate(endPoint,
                                                   (key) =>
            {
                var val = new PendingConnection(key);
                Log.Info("Connecting to " + endPoint);
                Net.Connect(endPoint);

                var expiration = Task.Delay(TimeSpan.FromSeconds(ExpirationTimeout),
                                            val.Expiration.Token);
                expiration.ContinueWith((_) =>
                {
                    PendingConnection cont;
                    if (_pendingConnections.TryRemove(key, out cont))
                    {
                        cont.TCS.SetException(new ConnectionFailedException(key));
                    }
                });
                return val;
            },
                                                   (key, val) => val
                                                   ).TCS.Task);
        }
示例#5
0
 public void ConnectTo(ulong userID)
 {
     // ID comparison is used to decide who calls Connect and who calls Accept
     if (SocialPlatformManager.MyID < userID)
     {
         Net.Connect(userID);
         SocialPlatformManager.LogOutput("P2P connect to " + userID);
     }
 }
示例#6
0
    public void ConnectTo(ulong userID)
    {
        m_remoteID = userID;

        // ID comparison is used to decide who calls Connect and who calls Accept
        if (PlatformManager.MyID < userID)
        {
            Net.Connect(userID);
        }
    }
示例#7
0
 public void Connect()
 {
     if (Status == ConnectStatus.Disconnected)
     {
         App.SubscribeUpdate(Update);
         Net.Connect(IP, Port);
         ConnectTime = 0;
         Status      = ConnectStatus.Connecting;
         OnStatusChanged?.Invoke(Status);
     }
 }
示例#8
0
    // adds a remote player to establish a connection to, or accept a connection from
    public void AddRemotePlayer(RemotePlayer player)
    {
        if (!m_remotePlayers.ContainsKey(player.ID))
        {
            m_remotePlayers[player.ID]         = new RemotePlayerData();
            m_remotePlayers[player.ID].state   = PeerConnectionState.Unknown;
            m_remotePlayers [player.ID].player = player;

            // ID comparison is used to decide who Connects and who Accepts
            if (PlatformManager.MyID < player.ID)
            {
                Debug.Log("P2P Try Connect to: " + player.ID);
                Net.Connect(player.ID);
            }
        }
    }
    void StartClientConnection(int id, ulong userId, string oculusId)
    {
        Log("Starting connection to client " + oculusId + " [" + userId + "]");
        IsTrue(id != 0);

        if (clients[id].state != Disconnected)
        {
            DisconnectClient(id);
        }

        clients[id].state             = Connecting;
        clients[id].oculusId          = oculusId;
        clients[id].userId            = userId;
        clients[id].connectionStarted = renderTime;
        Net.Connect(userId);
    }
示例#10
0
    void StartClientConnection(int clientIndex, ulong userId, string oculusId)
    {
        Debug.Log("Starting connection to client " + oculusId + " [" + userId + "]");

        Assert.IsTrue(clientIndex != 0);

        if (client[clientIndex].state != ClientState.Disconnected)
        {
            DisconnectClient(clientIndex);
        }

        client[clientIndex].state    = ClientState.Connecting;
        client[clientIndex].oculusId = oculusId;
        client[clientIndex].userId   = userId;
        client[clientIndex].timeConnectionStarted = renderTime;

        Net.Connect(userId);
    }
示例#11
0
    void ConnectionStateChangedCallback(Message <NetworkingPeer> msg)
    {
        Debug.LogFormat("Connection state to {0} changed to {1}", msg.Data.ID, msg.Data.State);

        if (msg.Data.ID == m_remoteID)
        {
            m_state = msg.Data.State;

            if (m_state == PeerConnectionState.Timeout &&
                // ID comparison is used to decide who calls Connect and who calls Accept
                PlatformManager.MyID < m_remoteID)
            {
                // keep trying until hangup!
                Net.Connect(m_remoteID);
            }
        }

        PlatformManager.SetBackgroundColorForState();
    }
示例#12
0
    void ConnectionStateChangedCallback(Message<NetworkingPeer> msg)
    {
        PlatformManager.LogOutput("P2P state to " + msg.Data.ID + " changed to  " + msg.Data.State):

        RemotePlayer remote = PlatformManager.GetRemoteUser(msg.Data.ID):
        if (remote != null)
        {
            remote.p2pConnectionState = msg.Data.State:

            if (msg.Data.State == PeerConnectionState.Timeout &&
                // ID comparison is used to decide who calls Connect and who calls Accept
                PlatformManager.MyID < msg.Data.ID)
            {
                // keep trying until hangup!
                Net.Connect(msg.Data.ID):
                PlatformManager.LogOutput("P2P re-connect to " + msg.Data.ID):
            }
        }
    }
示例#13
0
        static int _m_Connect(RealStatePtr L)
        {
            try {
                ObjectTranslator translator = ObjectTranslatorPool.Instance.Find(L);


                Net gen_to_be_invoked = (Net)translator.FastGetCSObj(L, 1);



                {
                    System.Collections.IEnumerator gen_ret = gen_to_be_invoked.Connect(  );
                    translator.PushAny(L, gen_ret);



                    return(1);
                }
            } catch (System.Exception gen_e) {
                return(LuaAPI.luaL_error(L, "c# exception:" + gen_e));
            }
        }
示例#14
0
 static void Main(string[] args)
 {
     Net net = new Net();
     net.Connect();
     while(true) {
         Tuple<NetEventType, Object> evt = net.PollNetworkEvent();
         if(evt != null) {
             Console.WriteLine(evt.GetFirst());
             switch(evt.GetFirst()) {
                 case NetEventType.CONNECT:
                     net.Write("ping\n");
                     break;
                 case NetEventType.DATA_READ:
                     Console.Write(evt.GetSecond());
                     net.Write("pong\n");
                     break;
                 case NetEventType.DISCONNECT:
                     Environment.Exit(0);
                     break;
             }
         }
     }
 }
        public Future <TNetPeer> ConnectToServer(IPEndPoint endPoint)
        {
            //check if we are already connected to this endpoint
            foreach (var pair in PeersByNetId)
            {
                if (endPoint.Equals(pair.Value.Channel.EndPoint))
                {
                    var future = new Future <TNetPeer>();
                    future.SetResult(pair.Value);
                    return(future);
                }
            }
            PendingConnection <TNetPeer> pendingConnection;

            if (!_pendingConnections.TryGetValue(endPoint, out pendingConnection))
            {
                pendingConnection = new PendingConnection <TNetPeer>(endPoint);
                _pendingConnections.Add(endPoint, pendingConnection);
                Net.Connect(endPoint);
            }

            return(pendingConnection.Future);
        }
示例#16
0
        public Task <INetChannel> Connect(IPEndPoint endPoint, CancellationToken cancellationToken)
        {
            //check if we are already connected to this endpoint
            foreach (var pair in ChannelsById)
            {
                if (endPoint.Equals(pair.Value.TransportChannel.EndPoint))
                {
                    return(Task.FromResult((INetChannel)pair.Value));
                }
            }

            return(_pendingConnections.AddOrUpdate(endPoint,
                                                   (key) =>
            {
                var val = new PendingConnection(key);
                _logger.ConnectingTo(this, endPoint);
                Net.Connect(endPoint);

                var expiration = Task.Delay(TimeSpan.FromSeconds(_config.ConnectTimeoutSec), val.Expiration.Token);
                expiration.ContinueWith(task =>
                {
                    if (!task.IsCanceled)
                    {
                        _logger.ConnectionHasTimedOut(this, endPoint);
                        PendingConnection cont;
                        if (_pendingConnections.TryRemove(key, out cont))
                        {
                            cont.TCS.SetException(new ConnectionFailedException(key));
                        }
                    }
                }, cancellationToken);
                return val;
            },
                                                   (key, val) => val
                                                   ).TCS.Task);
        }
示例#17
0
 public override void Update(GameTime gameTime)
 {
     if (Program.Game.IsActive)
     {
         if (Net.Peer == null)
         {
             if (Keyboard.Pressed(Keys.F1))
             {
                 Game1.Scene = new Scenes.Game(32);
                 Net.Host(6121, Scenes.Game.PlayerCount);
                 PlayerSpatialHash.Add(Scenes.Game.Self = Scenes.Game.AddPlayer(null));
                 Net.PlayerState[Scenes.Game.Self.ID]   = Player.NetState.Playing;
                 Scenes.Game.MakeServer();
             }
             else if (Keyboard.Pressed(Keys.F2))
             {
                 Net.Connect("25.73.181.13", 6121);
                 Scenes.Game.MakeClient();
             }
         }
     }
     Net.Update();
     base.Update(gameTime);
 }
示例#18
0
    // When someone joins or leaves, do add or remove
    private void OnRoomUpdateCallback(Message <Room> message)
    {
        if (message.IsError)
        {
            Debug.LogError("Room connecton error - " + message.GetError().Message);
        }
        else
        {
            room = message.GetRoom();

            StringBuilder roomMessage = new StringBuilder("Room update - ");

            // If we are just joining the room and someone else is already there, we
            //   need to update state
            bool userNeedsStateUpdate = !userInRoom &&
                                        (room.UsersOptional.Count > 1);

            foreach (var user in room.UsersOptional)
            {
                roomMessage.Append(user.OculusID + " ");

                if (user.ID == localUser.ID)
                {
                    if (!userInRoom)
                    {
                        userInRoom = true;
                        UnityUserReporting.CurrentClient.LogEvent(UserReportEventLevel.Info, "User joined room");
                    }
                }
                else
                {
                    if (!remoteConnectionStates.ContainsKey(user.ID))
                    {
                        remoteConnectionStates.Add(user.ID, new ConnectionStates()
                        {
                            username = user.OculusID
                        });
                    }

                    if (ShouldOwnConnection(user.ID))
                    {
                        UnityUserReporting.CurrentClient.LogEvent(UserReportEventLevel.Info, "Initiating net and voip to " + user.ID.ToString());

                        // Network state
                        if (remoteConnectionStates[user.ID].networkState == ConnectionState.Disconnected)
                        {
                            Net.Connect(user.ID);
                            remoteConnectionStates[user.ID].networkState = ConnectionState.Connecting;
                            remoteConnectionStates[user.ID].netTimeouts  = 0;
                        }
                        else
                        {
                            UnityUserReporting.CurrentClient.LogEvent(UserReportEventLevel.Info, "Skipping net connection since already connected to " + user.ID.ToString());
                        }

                        // VOIP state
                        if (remoteConnectionStates[user.ID].voipState == ConnectionState.Disconnected)
                        {
                            Voip.Start(user.ID);
                            remoteConnectionStates[user.ID].voipState    = ConnectionState.Connecting;
                            remoteConnectionStates[user.ID].voipTimeouts = 0;
                        }
                        else
                        {
                            UnityUserReporting.CurrentClient.LogEvent(UserReportEventLevel.Info, "Skipping voip connection since already connected to " + user.ID.ToString());
                        }
                    }
                    else
                    {
                        UnityUserReporting.CurrentClient.LogEvent(UserReportEventLevel.Info, "Skipping since don't own connection to " + user.ID.ToString());
                    }

                    // If someone was in the room before us, ask for the state
                    // once we connect.
                    if (userNeedsStateUpdate &&
                        (remoteConnectionStates[user.ID].networkState == ConnectionState.Connected))
                    {
                        OnRequestStateUpate(user.ID);
                        userNeedsStateUpdate = false;
                    }
                }
            }

            UnityUserReporting.CurrentClient.LogEvent(UserReportEventLevel.Info, roomMessage.ToString());

            if (userNeedsStateUpdate)
            {
                UnityUserReporting.CurrentClient.LogEvent(UserReportEventLevel.Info, "State update request pending");
                pendingStateUpdateRequest = true;
            }
        }
    }
示例#19
0
    void OnConnectionStateChangedCallback(Message <NetworkingPeer> message)
    {
        if (message.IsError)
        {
            Debug.LogError("Net connecton error - " + message.GetError().Message);
        }
        else
        {
            NetworkingPeer peer = message.GetNetworkingPeer();

            if (!remoteConnectionStates.ContainsKey(peer.ID))
            {
                remoteConnectionStates.Add(peer.ID, new ConnectionStates()
                {
                    username = peer.ID.ToString()
                });
            }

            switch (peer.State)
            {
            case PeerConnectionState.Connected:
                UnityUserReporting.CurrentClient.LogEvent(UserReportEventLevel.Info, "Net connected to " + peer.ID.ToString() +
                                                          ". State was " + remoteConnectionStates[peer.ID].networkState.ToString());

                remoteConnectionStates[peer.ID].networkState = ConnectionState.Connected;

                if (!remoteAvatars.ContainsKey(peer.ID))
                {
                    remoteAvatars.Add(peer.ID, createAvatar(peer.ID));
                }

                if (pendingStateUpdateRequest)
                {
                    OnRequestStateUpate(peer.ID);
                }

                break;

            case PeerConnectionState.Timeout:

                UnityUserReporting.CurrentClient.LogEvent(UserReportEventLevel.Info, "Net timeout for " + peer.ID.ToString() +
                                                          ". State was " + remoteConnectionStates[peer.ID].networkState.ToString());

                if (IsUserInRoom(peer.ID) && ShouldOwnConnection(peer.ID) &&
                    (remoteConnectionStates[peer.ID].networkState == ConnectionState.Connecting))
                {
                    UnityUserReporting.CurrentClient.LogEvent(UserReportEventLevel.Info,
                                                              "Net attempting reconnect to " + peer.ID.ToString() +
                                                              ". Attempt # " + remoteConnectionStates[peer.ID].netTimeouts +
                                                              ". State was " + remoteConnectionStates[peer.ID].networkState.ToString());
                    Net.Connect(peer.ID);
                    remoteConnectionStates[peer.ID].networkState = ConnectionState.Connecting;
                    remoteConnectionStates[peer.ID].netTimeouts += 1;
                }
                else
                {
                    remoteConnectionStates[peer.ID].networkState = ConnectionState.Disconnected;
                }

                if (remoteAvatars.ContainsKey(peer.ID))
                {
                    remoteAvatars.Remove(destroyAvatar(peer.ID));
                }

                break;

            case PeerConnectionState.Closed:

                UnityUserReporting.CurrentClient.LogEvent(UserReportEventLevel.Info, "Net disconnect from " + peer.ID.ToString() +
                                                          ". State was " + remoteConnectionStates[peer.ID].networkState.ToString());

                if (IsUserInRoom(peer.ID) && ShouldOwnConnection(peer.ID) &&
                    (remoteConnectionStates[peer.ID].networkState != ConnectionState.Disconnecting))
                {
                    UnityUserReporting.CurrentClient.LogEvent(UserReportEventLevel.Info,
                                                              "Net attempting reconnect to " + peer.ID.ToString() +
                                                              ". Reconnect # " + remoteConnectionStates[peer.ID].netReconnects +
                                                              ". State was " + remoteConnectionStates[peer.ID].networkState.ToString());
                    Net.Connect(peer.ID);
                    remoteConnectionStates[peer.ID].networkState   = ConnectionState.Reconnecting;
                    remoteConnectionStates[peer.ID].netReconnects += 1;
                }
                else
                {
                    remoteConnectionStates[peer.ID].networkState = ConnectionState.Disconnected;
                }

                if (remoteAvatars.ContainsKey(peer.ID))
                {
                    remoteAvatars.Remove(destroyAvatar(peer.ID));
                }

                break;

            default:
                UnityUserReporting.CurrentClient.LogEvent(UserReportEventLevel.Warning, "Net unexpected state from " + peer.ID.ToString());
                Debug.LogError("Unexpected connection state");
                break;
            }
        }
    }
示例#20
0
    // Use this for initialization
    void Start()
    {
        var config = new ClientConfiguration(ip, port);

        Net.Connect(config);
    }
示例#21
0
        static void Main(string[] args)
        {
            mNet = new Net();
            mNet.ConnectionClosed += mNet_ConnectionClosed;
            mAudioOut = new AudioOut(mNet.AudioOutStream);
            mAudioIn = new AudioIn_KinectXbox(mNet.AudioInStream);

            string server = "127.0.0.1";
            int port = 31337;
            bool retryConnects = true;

            //parse arguments

            //setup

            while (true)
            {
                //connect to server
                if (!mNet.Connected)
                {
                    if (!mNet.Connect(server, port))
                    {
                        Console.Write("Err: failed to connect.");
                        if (retryConnects)
                        {
                            Console.WriteLine("     Waiting 5s and then will retry");
                            Thread.Sleep(5000);
                            continue;
                        }
                        else
                        {
                            break;
                        }
                    }
                }

                //enter message loop
                Net.EMSG_TYPE msg = mNet.Recv(true); //note this may still block for a short time
                switch (msg)
                {
                    case Net.EMSG_TYPE.CONFIG:
                        Console.WriteLine("Received config, sending ready");
                        mNet.Send(Net.EMSG_TYPE.READY);
                        break;
                    case Net.EMSG_TYPE.START:
                        Console.WriteLine("Received start");
                        mAudioIn.Start();
                        break;
                    case Net.EMSG_TYPE.STOP:
                        Console.WriteLine("Received stop");
                        mAudioIn.Stop();
                        break;
                    case Net.EMSG_TYPE.GETBASE:
                        Console.WriteLine("Received baseline request");
                        mNet.Send(Net.EMSG_TYPE.BASELINE);
                        break;
                    case Net.EMSG_TYPE.AUDIOOUT:
                        //mAudioOut.DataReceived();
                        break;
                    default:
                        break;
                }
                //Thread.Sleep(50); //ms
            }
        }