Beispiel #1
0
    private void RecieveMessage(IAsyncResult ar)
    {
        Networker networker = (Networker)ar.AsyncState;

        try{
            int bytesRead = networker.stream.EndRead(ar);
            if (bytesRead == 0)
            {
                networker.stream.BeginRead(networker.readBuffer, 0, 256, new AsyncCallback(RecieveMessage), networker);
                return;
            }

            // string responseData = networker.readBuffer.ByteArrayToObject<string>();
            MessageType type          = (MessageType)networker.readBuffer[0];
            int         messageLength = networker.readBuffer[1];

            // byte[] buf = new byte[messageLength];
            // for(int i = 2; i < bytesRead; i++)
            //     buf[i-2] = networker.readBuffer[i];

            string responseData = System.Text.Encoding.ASCII.GetString(networker.readBuffer, 2, messageLength);
            Debug.Log($"Response from server: {responseData}");
        } catch (Exception e) {
            Debug.Log($"Failed to read from socket:\n{e}");
        }
    }
 public void SyncReceive(byte[] data)
 {
     if (!this.VerifyReceive())
     {
         return;
     }
     this.last        = this.Read(data);
     this.needsUpdate = true;
     if (this.syncUpdateRate == SyncUpdateRate.UpdateImmediate)
     {
         this.SyncUpdate();
     }
     if (Networker.mode == NetworkerMode.Client)
     {
     }
     if (Networker.mode == NetworkerMode.Server)
     {
         if (this.serverSyncOptions.Has("SendUponReceiving"))
         {
             int clientID  = this.serverSyncOptions.Has("OnlyOwner") ? Networker.GetActiveID() : -1;
             int excludeID = this.serverSyncOptions.Has("ExcludeOwner") ? Networker.GetActiveID() : -1;
             Networker.SendDataToClients(this.eventName, this.GetBytes(), clientID, excludeID);
         }
     }
 }
 void Awake()
 {
     if (instance == null)
     {
         instance = this;
     }
 }
Beispiel #4
0
 void Init()
 {
     if (Inited || MyAPIGateway.Session == null)
     {
         return;
     }
     try
     {
         Networker.Init(ModID);
         Networker.RegisterHandler("LaserSession", MessageHandler);
         MyAPIGateway.Utilities.MessageEntered += Utilities_MessageEntered;
         Settings = new LaserSettings();
         if (MyAPIGateway.Multiplayer.IsServer)
         {
             LoadSettings();
         }
         else
         {
             Networker.SendToServer("LaserSession", "AskingSettings", null);
         }
     }
     catch (Exception Scrap)
     {
         LogError("Init", Scrap);
     }
     Inited = true;
 }
Beispiel #5
0
 private void Update()
 {
     if (weaponManager.isFiring != previousFiringState)
     {
         previousFiringState         = weaponManager.isFiring;
         lastFiringMessage.weaponIdx = (int)traverse.Field("weaponIdx").GetValue();
         Debug.Log("combinedWeaponIdx = " + lastFiringMessage.weaponIdx);
         lastFiringMessage.UID        = networkUID;
         lastStoppedFiringMessage.UID = networkUID;
         if (weaponManager.isFiring)
         {
             if (Networker.isHost)
             {
                 Networker.SendGlobalP2P(lastFiringMessage, Steamworks.EP2PSend.k_EP2PSendReliable);
             }
             else
             {
                 Networker.SendP2P(Networker.hostID, lastFiringMessage, Steamworks.EP2PSend.k_EP2PSendReliable);
             }
         }
         else
         {
             if (Networker.isHost)
             {
                 Networker.SendGlobalP2P(lastStoppedFiringMessage, Steamworks.EP2PSend.k_EP2PSendReliable);
             }
             else
             {
                 Networker.SendP2P(Networker.hostID, lastStoppedFiringMessage, Steamworks.EP2PSend.k_EP2PSendReliable);
             }
         }
     }
 }
    public void ToggleReady(bool newVal, bool forceReset = false)
    {
        Networker   networker        = GameObject.FindObjectOfType <Networker>();
        MessageType readyMessageType = newVal ? MessageType.Ready : MessageType.Unready;

        networker?.SendMessage(new Message(readyMessageType));
        SetMode(newVal ? Mode.Ready : Mode.NotReady);
        lobby?.ReadyLocal(newVal);

        propertyBlock.SetFloat("_HighlightEdges", newVal.BoolToInt());
        meshRenderer.SetPropertyBlock(propertyBlock);
        hexesToOutline.ForEach(mr => mr.SetPropertyBlock(propertyBlock));

        if (newVal)
        {
            liftOnHover.LockUp();
        }
        else
        {
            liftOnHover.Unlock();
            if (forceReset && liftOnHover.isUp)
            {
                liftOnHover.Reset();
            }
        }
    }
Beispiel #7
0
    private void SendMessage(IAsyncResult ar)
    {
        Networker networker = (Networker)ar.AsyncState;

        try{
            networker.stream.EndWrite(ar);
            Debug.Log("Message sent.");

            lock (lockObj)
            {
                switch (networker.writeQueue.Count)
                {
                case 0:
                    networker.sending = false;
                    break;

                default:
                    if (networker.writeQueue.TryDequeue(out byte[] writeBuffer))
                    {
                        networker.sending = true;
                        stream.BeginWrite(writeBuffer, 0, writeBuffer.GetLength(0), new AsyncCallback(SendMessage), this);
                        return;
                    }
                    networker.sending = false;
                    return;
                }
            }
        } catch (Exception e) {
            Debug.Log($"Failed to write to socket:\n{e}");
        }
    }
Beispiel #8
0
        public virtual void Disconnect()
        {
#if FN_WEBSERVER
            webserver.Stop();
#endif

            Networker.objectCreated -= CreatePendingObjects;

            if (Networker != null)
            {
                Networker.Disconnect(false);
            }

            if (sqpServer != null)
            {
                sqpServer.ShutDown();
            }

            NetWorker.EndSession();

            NetworkObject.ClearNetworkObjects(Networker);
            pendingObjects.Clear();
            pendingNetworkObjects.Clear();
            MasterServerNetworker = null;
            Networker             = null;
            Instance = null;
            Destroy(gameObject);
        }
Beispiel #9
0
        public override void UpdateOnceBeforeFrame()
        {
            try
            {
                if (Drill.CubeGrid.Physics?.Enabled != true || !Networker.Inited)
                {
                    NeedsUpdate |= MyEntityUpdateEnum.BEFORE_NEXT_FRAME;
                    if (!Networker.Inited)
                    {
                        Networker.Init(SessionCore.ModID);
                    }
                    return;
                }
                SyncHarvestEfficiency = new Syncer <float>(Drill, "HarvestEfficiency", 1, Checker: val => val >= 1 && val <= 4);
                SyncHarvestEfficiency.GotValueFromServer += Drill.UpdateVisual;
                Drill.PowerConsumptionMultiplier          = PowerConsumptionMultiplier();

                CheckInitControls();
                Load();

                SessionCore.SaveRegister(Save);
                NeedsUpdate |= MyEntityUpdateEnum.EACH_FRAME;
                DebugNote    = MyAPIGateway.Utilities.CreateNotification($"{Drill?.CustomName}", int.MaxValue, "Blue");
                Owner        = MyAPIGateway.Players.GetPlayer(Drill.OwnerId);
                if (SessionCore.Settings.Debug)
                {
                    DebugNote.Show();
                }
            }
            catch { }
        }
Beispiel #10
0
        /// <summary>
        /// Called when you want to remove all network objects from the Networker list for a scene
        /// </summary>
        /// <param name="buildIndex"></param>
        void UnloadSceneNetworkObjects(int buildIndex)
        {
            if (buildIndex >= 0)
            {
                List <NetworkObject> networkObjectsToDestroy = new List <NetworkObject>();

                // Gets all networkObjects related to the scene we are destorying
                Networker.IterateNetworkObjects(networkObject =>
                {
                    NetworkBehavior networkBehavior = (NetworkBehavior)networkObject.AttachedBehavior;
                    if (networkBehavior && networkBehavior.gameObject)
                    {
                        if (networkBehavior.gameObject.scene.buildIndex == buildIndex)
                        {
                            networkObjectsToDestroy.Add(networkObject);
                        }
                    }
                });

                Networker.ManualRemove(networkObjectsToDestroy);

                foreach (NetworkObject networkObject in networkObjectsToDestroy)
                {
                    pendingNetworkObjects.Remove(networkObject.CreateCode);
                }
            }
        }
Beispiel #11
0
    private static void HandleDisconnectEvent(int rec, int sID, int cID)
    {
        if (!isHost)
        {
            hasConnected = false;
            isStarted    = false;
            Networker.Shutdown();
            OnServerDisconnected(false, new ConnectionObj()
            {
                connID = -1
            });
        }
        else
        {
            long v = IDplayers[sID];
            IDplayers.Remove(sID);
            curPlayerIDs.Remove(v);
            playerHID.Remove(v);
            playerIDs.Remove(v);

            OnClientDisconnect(false, new ConnectionObj()
            {
                connID = userUUID - 1
            });
        }
    }
Beispiel #12
0
 void Update()
 {
     if (Networker.IsConnected)
     {
         Networker.Poll();
     }
 }
    private void LateUpdate()
    {
        if (turret == null)
        {
            return;
        }

        tick += Time.deltaTime;
        if (tick > 1.0f / tickRate)
        {
            tick = 0.0f;
            Vector3D dir = new Vector3D(turret.pitchTransform.forward);
            lastMessage.direction = dir;

            lastMessage.UID      = networkUID;
            lastMessage.turretID = turretID;
            if (Networker.isHost)
            {
                Networker.addToUnreliableSendBuffer(lastMessage);
            }
            else
            {
                NetworkSenderThread.Instance.SendPacketToSpecificPlayer(Networker.hostID, lastMessage, Steamworks.EP2PSend.k_EP2PSendUnreliable);
            }
        }
    }
    private void Awake()
    {
        networker = GameObject.FindObjectOfType <Networker>();
        button.onClick.AddListener(() => {
            if (teamChangePanel.isOpen)
            {
                return;
            }
            // This is AI mode, the AI always approves team changes
            if (networker == null)
            {
                lobby?.SwapAITeam();
            }
            else if (!networker.isHost)
            {
                // This is a client
                ReadyStartObjectButton ready = GameObject.FindObjectOfType <ReadyStartObjectButton>();
                if (ready != null && ready.mode == ReadyStartObjectButton.Mode.Ready)
                {
                    ready.ToggleReady(false, true);
                }
            }

            EventSystem.current.Deselect();
            networker?.ProposeTeamChange();
        });
    }
 public void SyncSend()
 {
     if (Networker.mode == NetworkerMode.Client)
     {
         if (this.clientSync != ClientSyncType.SendToServer)
         {
             return;
         }
         if (!this.HasChanged() && this.onlySendIfChanged)
         {
             return;
         }
         Networker.SendDataToServer(this.eventName, this.GetBytes());
     }
     if (Networker.mode == NetworkerMode.Server)
     {
         if (this.serverSync != ServerSyncType.SendToClients)
         {
             return;
         }
         if (!this.HasChanged() && this.onlySendIfChanged)
         {
             return;
         }
         Networker.SendDataToClients(this.eventName, this.GetBytes());
     }
 }
    public static bool Prefix(SAMLauncher __instance)
    {
        if (!Networker.isHost)
        {
            return(true);
        }
        Debug.Log("Beginning sam launch prefix.");
        int j = 0;

        Missile[] missiles = (Missile[])Traverse.Create(__instance).Field("missiles").GetValue();
        for (int i = 0; i < missiles.Length; i++)
        {
            if (missiles[i] != null)
            {
                Debug.Log("Found a suitable missile to attach a sender to.");
                MissileNetworker_Sender missileSender = missiles[i].gameObject.AddComponent <MissileNetworker_Sender>();
                missileSender.networkUID = Networker.GenerateNetworkUID();
                SAMHelper.SAMmissile     = missileSender.networkUID;
                return(true);
            }
        }
        Debug.Log("Could not find a suitable missile to attach a sender to.");
        SAMHelper.SAMmissile = 0;
        return(true);
        // __state = 0;
    }
        public void WaitReliable(FrameStream frame)
        {
            if (!frame.IsReliable)
            {
                return;
            }

            if (frame.UniqueReliableId == currentReliableId)
            {
                Networker.FireRead(frame, this);
                currentReliableId++;

                FrameStream next = null;
                while (true)
                {
                    if (!reliablePending.TryGetValue(currentReliableId, out next))
                    {
                        break;
                    }

                    reliablePending.Remove(currentReliableId++);
                    Networker.FireRead(next, this);
                }
            }
            else if (frame.UniqueReliableId > currentReliableId)
            {
                reliablePending.Add(frame.UniqueReliableId, frame);
            }
        }
Beispiel #18
0
    private void Awake()
    {
        if (button == null)
        {
            gameObject.GetComponent <Button>();
        }

        SceneTransition sceneTransition = GameObject.FindObjectOfType <SceneTransition>();

        button?.onClick.AddListener(() => {
            if (sceneTransition != null)
            {
                sceneTransition.Transition($"{sceneToLoad}");
            }
            else
            {
                SceneManager.LoadScene($"{sceneToLoad}");
            }

            if (sceneToLoad == "MainMenu")
            {
                Networker networker = GameObject.FindObjectOfType <Networker>();
                if (networker != null)
                {
                    Destroy(networker.gameObject);
                }
            }
        });
    }
Beispiel #19
0
    public void WeaponSet(Packet packet)
    {
        //This message has only been sent to us so no need to check UID
        List <HPInfo> hpInfos = new List <HPInfo>();
        List <int>    cm      = new List <int>();
        float         fuel    = 0.65f;

        HPEquippable lastEquippable = null;

        for (int i = 0; i < weaponManager.equipCount; i++)
        {
            lastEquippable = weaponManager.GetEquip(i);
            List <ulong> missileUIDS = new List <ulong>();
            if (lastEquippable.weaponType != HPEquippable.WeaponTypes.Gun &&
                lastEquippable.weaponType != HPEquippable.WeaponTypes.Rocket)
            {
                HPEquipMissileLauncher HPml = lastEquippable as HPEquipMissileLauncher;
                if (HPml.ml == null) //I think this could be null.
                {
                    break;
                }
                for (int j = 0; j < HPml.ml.missiles.Length; j++)
                {
                    //If they are null, they have been shot.
                    if (HPml.ml.missiles[i] == null)
                    {
                        missileUIDS.Add(0);
                        continue;
                    }

                    MissileNetworker_Sender sender = HPml.ml.missiles[i].gameObject.GetComponent <MissileNetworker_Sender>();
                    if (sender != null)
                    {
                        missileUIDS.Add(sender.networkUID);
                    }
                    else
                    {
                        Debug.LogError($"Failed to get NetworkUID for missile ({HPml.ml.missiles[i].gameObject.name})");
                    }
                }
            }

            hpInfos.Add(new HPInfo(
                            lastEquippable.gameObject.name.Replace("(Clone)", ""),
                            lastEquippable.weaponType,
                            missileUIDS.ToArray()));
        }

        for (int i = 0; i < cmManager.countermeasures.Count; i++)
        {
            cm.Add(cmManager.countermeasures[i].count);
        }

        fuel = fuelTank.fuel / fuelTank.totalFuel;

        Networker.SendP2P(Networker.hostID,
                          new Message_WeaponSet_Result(hpInfos.ToArray(), cm.ToArray(), fuel, networkUID),
                          Steamworks.EP2PSend.k_EP2PSendReliable);
    }
 public override void Start()
 {
     base.Start();
     if (Proxy.IsPlaying())
     {
         this.eventName = "Sync-" + this.path;
         Networker.AddEvent(this.eventName, this.SyncReceive);
     }
 }
Beispiel #21
0
        public ActionResult Modify()
        {
            string userId                  = User.Identity.GetUserId();
            ApplicationDbContext db        = new ApplicationDbContext();
            Networker            networker = db.Networkers.Where(n => n.UserId == userId).SingleOrDefault();

            ViewBag.Email = db.Users.Where(u => u.Id == userId).Select(u => u.Email);
            return(View(networker));
        }
Beispiel #22
0
        private void OnApplicationQuit()
        {
            if (Networker != null)
            {
                Networker.Disconnect(false);
            }

            NetWorker.EndSession();
        }
        protected virtual void OnApplicationQuit()
        {
            if (Networker != null)
            {
                Networker.Disconnect(false);
            }

            NetWorker.EndSession();
        }
Beispiel #24
0
        public override void UpdateOnceBeforeFrame()
        {
            try
            {
                if (RadarBlock.CubeGrid.Physics == null)
                {
                    NeedsUpdate |= MyEntityUpdateEnum.BEFORE_NEXT_FRAME;
                    return;
                }

                if (!Networker.Inited)
                {
                    Networker.Init(907384096);
                }
                if (!Controls.InitedRadarControls)
                {
                    Controls.InitRadarControls();
                }

                NeedsUpdate |= MyEntityUpdateEnum.EACH_10TH_FRAME;
                GetMaxPower();
                Term = RadarBlock.CubeGrid.GetTerminalSystem();

                RadarPower           = new AutoSet <float>(RadarBlock, "Power", 1000, x => x >= 0 && x <= MaxPower);
                ShowMarkers          = new AutoSet <bool>(RadarBlock, "ShowMarkers", true, null);
                ShowRoids            = new AutoSet <bool>(RadarBlock, "ShowRoids", true, null);
                ActiveRadar          = new AutoSet <bool>(RadarBlock, "Active", false, null);
                ShowOnlyHostiles     = new AutoSet <bool>(RadarBlock, "OnlyHostiles", true, null);
                ShowFloating         = new AutoSet <bool>(RadarBlock, "Floating", false, null);
                ShowWorkingGridsOnly = new AutoSet <bool>(RadarBlock, "ShowWorkingGridsOnly", false, null);

                PowerModule.InitResourceSink();
                PersistenceModule.Load();
                RadarBlock.AppendingCustomInfo += RadarBlock_AppendingCustomInfo;
                RadarBlock.OnMarkForClose      += OnMarkForClose;
                Debug.Write($"Added radar {RadarBlock.EntityId}");
                if (RadarCore.Debug)
                {
                    TestNote = MyAPIGateway.Utilities.CreateNotification($"{RadarBlock.CustomName}: enabled;", int.MaxValue, "Green");
                }

                if (RadarCore.Debug)
                {
                    TestNote.Show();
                }

                RadarCore.DebugWrite("Testing", "TESTING", true);

                //MyRadarGrid = RadarBlock.CubeGrid.Components.Get<RadarableGrid>();
                if (MyRadarGrid == null)
                {
                    throw new Exception($"{RadarBlock.CustomName}.MyRadarGrid is null!");
                }
            }
            catch { }
        }
Beispiel #25
0
 private void Start()
 {
     if (_instance == null)
     {
         HarmonyInstance harmony = HarmonyInstance.Create("marsh.vtolvr.multiplayer.temperzFork");
         harmony.PatchAll(Assembly.GetExecutingAssembly());
     }
     _instance = this;
     Networker.SetMultiplayerInstance(this);
 }
Beispiel #26
0
    void Start()
    {
        networker   = GameObject.FindGameObjectWithTag("Networker").GetComponent <Networker>();
        guiRenderer = MenuGUI;

        // Adding listeners to the networker's events
        Networker.ClientConnected   += Networker_ClientConnected;
        Networker.ServerInitialized += Networker_ServerInitialized;
        Networker.Disconnected      += Networker_Disconnected;
    }
 public void SelectFriend(int index)
 {
     JoinButton.SetActive(true);
     joinButtonText.text = $"Join {SteamFriends.GetFriendPersonaName(steamFriends[index].steamID)}";
     selectedFriend      = steamFriends[index].steamID;
     Log("User has selected " + SteamFriends.GetFriendPersonaName(steamFriends[index].steamID));
     Networker.SendP2P(steamFriends[index].steamID, new Message_LobbyInfoRequest(), EP2PSend.k_EP2PSendReliable); //Getting lobby info.
     selectionTF.position = steamFriends[index].transform.position;
     selectionTF.GetComponent <Image>().color = new Color(0.3529411764705882f, 0.196078431372549f, 0);
 }
Beispiel #28
0
 void SendSettings(ulong To = 0)
 {
     if (To != 0)
     {
         Networker.SendTo(To, "LaserSession", "ServerSettings", MyAPIGateway.Utilities.SerializeToBinary(Settings));
     }
     else
     {
         Networker.SendToAll("LaserSession", "ServerSettings", MyAPIGateway.Utilities.SerializeToBinary(Settings));
     }
 }
Beispiel #29
0
 private void SendMessage(bool isDestoryed)
 {
     if (Networker.isHost)
     {
         Networker.SendGlobalP2P(lastMessage, isDestoryed ? Steamworks.EP2PSend.k_EP2PSendReliable : Steamworks.EP2PSend.k_EP2PSendUnreliable);
     }
     else
     {
         Networker.SendP2P(Networker.hostID, lastMessage, isDestoryed ? Steamworks.EP2PSend.k_EP2PSendReliable : Steamworks.EP2PSend.k_EP2PSendUnreliable);
     }
 }
Beispiel #30
0
        private async void UdpClientAction()
        {
            try
            {
                udpClient = new UdpClient(4536);
                while (IsStarted)
                {
                    var udpReceiveResult = await udpClient.ReceiveAsync();

                    if (!udpReceiveResult.RemoteEndPoint.Address.ToString().Equals(Networker.GetLocalIp()))
                    {
                        var defconStatus = Encoding.ASCII.GetString(udpReceiveResult.Buffer);
                        if (int.TryParse(defconStatus, out int parsedDefconStatus))
                        {
                            if (parsedDefconStatus > 0 && parsedDefconStatus < 6)
                            {
                                new SettingsService().SaveSetting("DefconStatus", defconStatus.ToString());

                                Intent widgetIntent = new Intent(this, typeof(MyDefconWidget));
                                widgetIntent.SetAction("com.marcusrunge.MyDEFCON.DEFCON_UPDATE");
                                widgetIntent.PutExtra("DefconStatus", defconStatus.ToString());

                                Intent statusReceiverIntent = new Intent(this, typeof(ForegroundDefconStatusReceiver));
                                statusReceiverIntent.SetAction("com.marcusrunge.MyDEFCON.STATUS_RECEIVER_ACTION");
                                statusReceiverIntent.PutExtra("DefconStatus", defconStatus.ToString());

                                SendBroadcast(widgetIntent);
                                SendBroadcast(statusReceiverIntent);

                                if (_settingsService.GetSetting <bool>("isStatusUpdateAlertEnabled"))
                                {
                                    Notifier.AlertWithVibration();
                                    Notifier.AlertWithAudioNotification(this, _settingsService.GetSetting <int>("StatusUpdateAlertSelection"));
                                }
                            }
                            else if (parsedDefconStatus == 0 && _settingsService.GetSetting <bool>("IsMulticastEnabled") && DateTimeOffset.Now > _lastConnect.AddSeconds(5))
                            {
                                Intent tcpActionIntent = new Intent(this, typeof(TcpActionReceiver));
                                tcpActionIntent.SetAction("com.marcusrunge.MyDEFCON.TCP_ACTION");
                                tcpActionIntent.PutExtra("RemoteEndPointAddress", udpReceiveResult.RemoteEndPoint.Address.ToString());
                                SendBroadcast(tcpActionIntent);
                                _lastConnect = DateTimeOffset.Now;
                            }
                        }
                    }
                }
                if (udpClient != null)
                {
                    udpClient.Close();
                    udpClient.Dispose();
                }
            }
            catch { }
        }
Beispiel #31
0
    void Start()
    {
        networker = GameObject.FindGameObjectWithTag("Networker").GetComponent<Networker>();
        guiRenderer = MenuGUI;

        // Adding listeners to the networker's events
        Networker.ClientConnected += Networker_ClientConnected;
        Networker.ServerInitialized += Networker_ServerInitialized;
        Networker.Disconnected += Networker_Disconnected;
    }