public void Setup(bool is_host) { this.is_host = is_host; GameObject.Find("Join/Host").SetActive(false); SetupVariables(); if(is_host) { socket = Host_Actions.Host(); // Debug_View_Mediator.Setup_Debug(); socket.connected += delegate { ServerWaiting(); }; socket.playerConnected += delegate { ServerWaiting(); }; } else { socket = Client_Actions.Connect(); // Debug_View_Mediator.Setup_Debug(); socket.connected += delegate { socket.AddCustomDataReadEvent(EventHelper.GetEventId("ALL_CLIENTS_JOINED"), delegate (NetworkingPlayer arg1, NetworkingStream arg2) { Debug_Console.i.add("All clients have joined"); Turn_Controller.instance.server_players = (Server_Player_Model) EasySerialization.EasyDeserialize<Server_Player_Model>(ref arg2); state = 1; }); manager.SetActive(true); }; } }
public void StartClient() { instance = this; socket = Networking.Connect(login_server_ip, login_server_port, Networking.TransportationProtocolType.UDP); socket.connected += delegate { Debug_Console.i.add("Connected"); Networking.SetPrimarySocket(socket); RegisterEvents(); MainThreadManager.Run(delegate { show_on_connect.SetActive(true); }); }; }
public override void Setup(ref NetWorker socket) { base.Setup(ref socket); socket.AddCustomDataReadEvent(EventHelper.GetEventId("SERVER_REQUEST"), delegate { Debug_Console.i.add("sending server request"); }); // socket.AddCustomDataReadEvent ("COMBAT_REGISTER", delegate { // Debug_View_Mediator.i.add("sending combat register"); // }); Debug_Console.i.add("Client controller setup"); }
public void StartServer() { socket = Networking.Host(login_server_port, Networking.TransportationProtocolType.UDP, 9999); socket.connected += delegate { Debug_Console.i.add("Connected"); Networking.SetPrimarySocket(socket); RegisterEvents(); }; socket.playerConnected += delegate (NetworkingPlayer player) { Debug_Console.i.add("Player Connected"); server_model.unverified.Add(new Login_Server_Player_Model(player.NetworkId, player.Ip)); }; socket.playerDisconnected += delegate (NetworkingPlayer player) { Debug_Console.i.add("Player Disconnected"); server_model.RemoveUser(player.NetworkId); }; }
public override void Setup(ref NetWorker socket) { base.Setup(ref socket); socket.AddCustomDataReadEvent(EventHelper.GetEventId("SERVER_REQUEST"), ReadRequest); // socket.AddCustomDataReadEvent ("COMBAT_REGISTER", ReadCombatRegister); SmartObject obj = new SmartObject(); SmartObject add = new SmartObject(); Client_Model[] players = Turn_Controller.instance.server_players.players.ToArray(); int entity_count = 0; for(int i = 0; i < players.Length; i++) { Entity_Model_Army army = Entity_Model_Army.GenerateRandomArmy(ref players[i], 2); for(int i2 = 0; i2 < army.entity_army.Length; i2++) { add.AddEntity("Entity_" + entity_count, army.entity_army[i2]); entity_count++; } } Debug_Console.i.add("Host controller setup"); add.AddInt("length", entity_count); obj.AddSmartObject("Additions", add); BMSByte bms_byte = EasySerialization.EasySerialize(obj); StartCoroutine("Delayed", bms_byte); }
/// <summary> /// Gets the updated frame of a given type, number, target value, and current value /// </summary> /// <param name="type">Type of frame we want to update</param> /// <param name="frameNumber">The frame number of what the server is</param> /// <param name="value">The target value of the server</param> /// <param name="currentValue">The current value of the client</param> /// <returns></returns> public Vector3 UpdateFrame(NetWorker owningNetworker, AuthoritativeFrameType type, Vector3 currentValue, byte serverFrame, Vector3 serverValue, ref Vector3 previousValue) { switch (type) { case AuthoritativeFrameType.Position: if (!_trackPos) return currentValue; break; case AuthoritativeFrameType.Rotation: if (!_trackRotation) return currentValue; break; case AuthoritativeFrameType.Scale: if (!_trackScale) return currentValue; break; } //ADD/UPDATE CLIENT FRAME HandleClient(type, currentValue, ref previousValue); return FinishFrame(owningNetworker, type, currentValue, serverFrame, serverValue); }
/// <summary> /// This method is called when the host server button is clicked /// </summary> public void StartServer() { // Create a host connection socket = Networking.Host((ushort)port, protocolType, playerCount, IsWinRT); if (socket is CrossPlatformUDP) { ((CrossPlatformUDP)socket).packetDropSimulationChance = packetDropSimulationChance; ((CrossPlatformUDP)socket).networkLatencySimulationTime = networkLatencySimulationTime; } if (!string.IsNullOrEmpty(masterServerIp)) { socket.connected += delegate() { ForgeMasterServer.RegisterServer(masterServerIp, (ushort)port, playerCount, "My Awesome Game Name", "Deathmatch", "Thank you for your support!", sceneName: sceneName); }; socket.playerConnected += UpdatePlayerCount; socket.playerDisconnected += UpdatePlayerCount; } Go(); }
public void TCPLocal() { socket = Networking.Connect("127.0.0.1", (ushort)port, protocolType, IsWinRT); Go(); }
/// <summary> /// Tells the client to change their scene to the given scene. This is often called /// after the server has changed to that scene to ensure that the server will always /// load up the scene before the client does /// </summary> /// <param name="netWorker">The current <see cref="NetWorker"/> that will be sending the message</param> /// <param name="targetPlayer">The particular player that will be receiving this message</param> /// <param name="sceneName">The name of the scene in which the client should load</param> public static void ChangeClientScene(NetWorker netWorker, NetworkingPlayer targetPlayer, string sceneName) { if (!netWorker.IsServer) throw new NetworkException("Only the server can call this method, the specified NetWorker is not a server"); BMSByte data = new BMSByte(); data.Clone(Encryptor.Encoding.GetBytes(sceneName)); data.InsertRange(0, new byte[1] { 2 }); netWorker.WriteRaw(targetPlayer, data); }
/// <summary> /// TODO /// </summary> /// <param name="id">Unique identifier to be used</param> /// <param name="netWorker">The NetWorker(Socket) to write with</param> /// <param name="data">Data to send over</param> /// <param name="reliableUDP">If this be a reliable UDP</param> public static void WriteCustom(string id, NetWorker netWorker, BMSByte data, NetworkingPlayer target, bool reliableUDP = false) { if (!netWorker.IsServer) throw new NetworkException("Currently this overload of WriteCustom is only supported being called on the server."); if (netWorker is CrossPlatformUDP) { netWorker.Write(id, target, new NetworkingStream().Prepare( netWorker, NetworkingStream.IdentifierType.Custom, null, data, NetworkReceivers.Others, reliableUDP, id ), reliableUDP); } else { netWorker.Write(target, new NetworkingStream().Prepare( netWorker, NetworkingStream.IdentifierType.Custom, null, data, NetworkReceivers.Others, reliableUDP, id )); } }
/// <summary> /// Write a custom raw byte message with a 1 byte header across the network /// </summary> /// <param name="id"></param> /// <param name="netWorker"></param> /// <param name="data"></param> public static void WriteRaw(NetWorker netWorker, BMSByte data) { if (data == null) { netWorker.ThrowException(new NetworkException(1000, "The data being written can not be null")); return; } if (data.Size == 0) { netWorker.ThrowException(new NetworkException(1001, "The data being sent can't be empty")); return; } data.InsertRange(0, rawTypeIndicator); netWorker.WriteRaw(data); }
/// <summary> /// Call an RPC method with a NetWorker(Socket) and arguments /// </summary> /// <param name="methodName">Method(Function) name to call</param> /// <param name="socket">The NetWorker(Socket) being used</param> /// <param name="arguments">Extra parameters passed in</param> public void RPC(string methodName, NetWorker socket, params object[] arguments) { RPC(methodName, socket, NetworkReceivers.All, arguments); }
/// <summary> /// Call an Unreliable RPC method on a NetWorker(Socket) with receivers and arguments /// </summary> /// <param name="methodName">Method(Function) name to call</param> /// <param name="socket">The NetWorker(Socket) being used</param> /// <param name="receivers">Who shall receive the RPC</param> /// <param name="arguments">The RPC function parameters to be passed in</param> public void URPC(string methodName, NetWorker socket, NetworkReceivers receivers, params object[] arguments) { MethodInfo rpc = GetStreamRPC(methodName, receivers, arguments); if (socket is CrossPlatformUDP) ((CrossPlatformUDP)socket).Write("BMS_INTERNAL_Rpc_" + methodName, rpcNetworkingStream, false); else socket.Write(rpcNetworkingStream); if (socket.IsServer && receivers != NetworkReceivers.Others && receivers != NetworkReceivers.OthersBuffered && receivers != NetworkReceivers.OthersProximity) rpc.Invoke(this, arguments); }
/// <summary> /// Used for the server to call an RPC method on a NetWorker(Socket) on a particular player /// </summary> /// <param name="methodName">Method(Function) name to call</param> /// <param name="socket">The NetWorker(Socket) being used</param> /// <param name="player">The NetworkingPlayer who will execute this RPC</param> /// <param name="arguments">The RPC function parameters to be passed in</param> public void AuthoritativeRPC(string methodName, NetWorker socket, NetworkingPlayer player, bool runOnServer, params object[] arguments) { MethodInfo rpc = GetStreamRPC(methodName, NetworkReceivers.All, arguments); if (socket is CrossPlatformUDP) ((CrossPlatformUDP)socket).Write("BMS_INTERNAL_Rpc_" + methodName, player, rpcNetworkingStream, true); else socket.Write(player, rpcNetworkingStream); if (socket.IsServer && runOnServer) { CallOnMainThread(delegate(object[] args) { rpc.Invoke(this, arguments); }); } }
/// <summary> /// Setup the Simple Networked Monobehavior stack with a NetWorker, owner, network id, and owner id /// </summary> /// <param name="owningSocket">The NetWorker to be setup with</param> /// <param name="isOwner">If this object is the owner</param> /// <param name="networkId">The NetworkID for this Simple Networked Monobehavior</param> /// <param name="ownerId">The OwnerID for this Simple Networked Monobehavior</param> public virtual void Setup(NetWorker owningSocket, bool isOwner, ulong networkId, ulong ownerId) { if (owningSocket == null) ThrowNetworkerException(); OwningNetWorker = owningSocket; IsOwner = isOwner; OwnerId = ownerId; NetworkedId = networkId; networkedBehaviors.Add(NetworkedId, this); if (OwningNetWorker.IsServer) { foreach (NetworkingPlayer player in OwningNetWorker.Players) { if (ownerId == player.NetworkId) { OwningPlayer = player; break; } } } else if (OwningNetWorker.Me != null && ownerId == OwningNetWorker.Me.NetworkId) OwningPlayer = OwningNetWorker.Me; NetworkStart(); }
/// <summary> /// Write to the TCP given a NetWorker(Socket) with a stream of data /// </summary> /// <param name="socket">The NetWorker(Socket) to write with</param> /// <param name="stream">The stream of data to be written</param> public static void WriteTCP(NetWorker socket, NetworkingStream stream) { socket.Write(stream); }
/// <summary> /// TODO /// </summary> /// <param name="id">Unique identifier to be used</param> /// <param name="netWorker">The NetWorker(Socket) to write with</param> /// <param name="data">Data to send over</param> /// <param name="reliableUDP">If this be a reliable UDP</param> public static void WriteCustom(string id, NetWorker netWorker, BMSByte data, bool reliableUDP = false, NetworkReceivers recievers = NetworkReceivers.All) { if (netWorker is CrossPlatformUDP) { netWorker.Write(id, new NetworkingStream().Prepare( netWorker, NetworkingStream.IdentifierType.Custom, null, data, recievers, reliableUDP, id ), reliableUDP); } else { netWorker.Write(new NetworkingStream().Prepare( netWorker, NetworkingStream.IdentifierType.Custom, null, data, recievers, reliableUDP, id )); } }
public void StartClient() { socket = Networking.Connect(host, (ushort)port, protocolType, IsWinRT); Go(); }
/// <summary> /// Allows the server to send a raw message to a particular player /// </summary> /// <param name="netWorker"></param> /// <param name="targetPlayer"></param> /// <param name="data"></param> public static void WriteRaw(NetWorker netWorker, NetworkingPlayer targetPlayer, BMSByte data) { data.InsertRange(0, new byte[1] { 1 }); netWorker.WriteRaw(targetPlayer, data); }
/// <summary> /// This method is called when the host server button is clicked /// </summary> public void StartServer() { // Create a host connection socket = Networking.Host((ushort)port, protocolType, playerCount, false); Go(); }
/// <summary> /// Determine if a NetWorker(Socket) reference is connected, (Dumbly returns socket.Connected) /// </summary> /// <param name="socket">NetWorker(Socket) to be checked</param> /// <returns>True if the referenced NetWorker has established a connection</returns> public static bool IsConnected(NetWorker socket) { return socket.Connected; }
/// <summary> /// Used to assign the <see cref="Networking.PrimarySocket"/> object to the specified <see cref="NetWorker"/> /// </summary> /// <param name="netWorker">The NetWorker that will be the primary socket</param> public static void SetPrimarySocket(NetWorker netWorker) { PrimarySocket = netWorker; if (PrimarySocket is CrossPlatformUDP) PrimaryProtocolType = ProtocolType.UDP; else PrimaryProtocolType = ProtocolType.TCP; }
public void StartClient() { host = ipAddressInput.text; if (string.IsNullOrEmpty(host.Trim())) { Debug.Log("No ip address provided to connect to"); return; } socket = Networking.Connect(host, (ushort)port, protocolType, IsWinRT); Go(); }
/// <summary> /// Disconnect a player on a given NetWorker(Socket) /// </summary> /// <param name="socket">NetWorker(Socket) to be disconnected from</param> /// <param name="player">The player reference to disconnect</param> /// <exception cref="NetworkException">Thrown when the <see cref="NetWorker"/> on the specified port is not a server</exception> /// <example> /// // Disconnect the first player on the primary socket /// Networking.Disconnect(Networking.PrimarySocket, Networking.PrimarySocket.Players[0]); /// </example> public static void Disconnect(NetWorker socket, NetworkingPlayer player) { if (!socket.IsServer) throw new NetworkException("Disconnecting players can only be managed by the server, the NetWorker on the specified port is not a server"); socket.Disconnect(player); }
public void StartClientLan() { #if !NETFX_CORE System.Net.IPEndPoint endpoint = Networking.LanDiscovery((ushort)port, 5000, protocolType, IsWinRT); #else IPEndPointWinRT endpoint = Networking.LanDiscovery((ushort)port, 5000, protocolType, IsWinRT); #endif if (endpoint == null) { Debug.Log("No server found on LAN"); return; } string ipAddress = string.Empty; ushort targetPort = 0; #if !NETFX_CORE ipAddress = endpoint.Address.ToString(); targetPort = (ushort)endpoint.Port; #else ipAddress = endpoint.ipAddress; targetPort = (ushort)endpoint.port; #endif socket = Networking.Connect(ipAddress, targetPort, protocolType, IsWinRT); Go(); }
/// <summary> /// Disconnect the specified <see cref="NetWorker"/> (socket) and remove it from the <see cref="Networking.Sockets"/> lookup /// </summary> /// <param name="socket">The socket <see cref="NetWorker"/> to be shut down</param> public static void Disconnect(NetWorker socket) { ushort[] keys = new ushort[Sockets.Keys.Count]; Sockets.Keys.CopyTo(keys, 0); for (int i = 0; i < keys.Length; i++) { if (Sockets[keys[i]] == socket) { socket.Disconnect(); Sockets[keys[i]] = null; Sockets.Remove(keys[i]); break; } } }
/// <summary> /// Setup this NetworkedMonoBehavior with the owner of this object along with the networked ID /// </summary> /// <param name="owningSocket">The socket that owns this object</param> /// <param name="isOwner">Is this the owner of this object</param> /// <param name="networkId">Network ID of who owns it</param> /// <param name="ownerId">The network identifyer for the player who owns this object</param> public override void Setup(NetWorker owningSocket, bool isOwner, ulong networkId, ulong ownerId, bool isSceneObject = false) { base.Setup(owningSocket, isOwner, networkId, ownerId, isSceneObject); bool foundServerAuthority = false, clientPrediction = false; foreach (NetworkedMonoBehavior behavior in GetComponents<NetworkedMonoBehavior>()) { if (behavior.serverIsAuthority) { foundServerAuthority = true; clientPrediction = behavior.clientSidePrediction; break; } } if (rigidbodyRef != null) { if ((!OwningNetWorker.IsServer && foundServerAuthority && !clientPrediction) || (!IsOwner && !foundServerAuthority)) { rigidbodyRef.constraints = RigidbodyConstraints.FreezeAll; rigidbodyRef.useGravity = false; } } if (isPlayer && OwningNetWorker.IsServer) serverTargetPlayer = OwningPlayer; if (turnedOffCollider) { if ((OwningNetWorker.IsServer && foundServerAuthority) || (IsOwner && !foundServerAuthority)) { turnedOffCollider = false; colliderRef.enabled = true; } } }
/// <summary> /// Writes a <see cref="NetworkingStream"/> to a particular <see cref="NetWorker"/> directly to a player (if the port is a server) /// </summary> /// <param name="socket">NetWorker(Socket) to write with</param> /// <param name="player">Player to be written to server</param> /// <param name="stream">The stream of data to be written</param> /// <exception cref="NetworkException">Thrown when there is not a <see cref="NetWorker"/> on the supplied port</exception> /// <exception cref="NetworkException">Thrown when the <see cref="NetWorker"/> on the specified port is not a server</exception> public static void Write(NetWorker socket, NetworkingPlayer player, NetworkingStream stream) { if (!socket.IsServer) throw new NetworkException("Writing to particular players can only be done by the server, the NetWorker on the specified port is not a server"); socket.Write(player, stream); }
private Vector3 FinishFrame(NetWorker owningNetworker, AuthoritativeFrameType type, Vector3 currentValue, byte serverFrame, Vector3 serverValue) { bool frameFound = false; int iter = 0; Vector3 pos = currentValue; switch (type) { case AuthoritativeFrameType.Position: if (_posLastFrame != serverFrame) { _posLastFrame = serverFrame; _posTimeStamp = Time.time; if (_positionFrameHistory.Count > 0) { for (int i = _positionFrameHistory.Count - 1; i >= 0; --i) { if (_positionFrameHistory[i].Frame == serverFrame) { frameFound = true; iter = i; break; } } if (frameFound) { _positionFrameHistory.RemoveRange(0, iter); _positionFrameHistory[0].FrameActualValue = serverValue; _positionFrameHistory[0].FrameValue = Vector3.zero; if (_positionFrameHistory.Count > 1) { _positionFrameHistory[1].FramePrevious = _positionFrameHistory[0].FrameActualValue; _positionFrameHistory[1].UpdateDelta(); } pos = serverValue; for (int i = 0; i < _positionFrameHistory.Count; ++i) pos += _positionFrameHistory[i].FrameValue; //Get the delta distance } } currentValue = pos; } else { if ((Time.time - _posTimeStamp) * 1000 > owningNetworker.PreviousServerPing + 100) { _posTimeStamp = Time.time; if (Vector3.Distance(currentValue, serverValue) > 0.1f) { currentValue = serverValue; _positionFrameHistory.Clear(); } } } break; case AuthoritativeFrameType.Rotation: if (_rotLastFrame != serverFrame) { _rotLastFrame = serverFrame; _rotTimeStamp = Time.time; if (_rotationFrameHistory.Count > 0) { for (int i = _rotationFrameHistory.Count - 1; i >= 0; --i) { if (_rotationFrameHistory[i].Frame == serverFrame) { frameFound = true; iter = i; break; } } if (frameFound) { _rotationFrameHistory.RemoveRange(0, iter); _rotationFrameHistory[0].FrameActualValue = serverValue; _rotationFrameHistory[0].FrameValue = Vector3.zero; if (_rotationFrameHistory.Count > 1) { _rotationFrameHistory[1].FramePrevious = _rotationFrameHistory[0].FrameActualValue; _rotationFrameHistory[1].UpdateDelta(); } pos = serverValue; for (int i = 0; i < _rotationFrameHistory.Count; ++i) pos += _rotationFrameHistory[i].FrameValue; //Get the delta distance } } currentValue = pos; } else { if ((Time.time - _rotTimeStamp) * 1000 > owningNetworker.PreviousServerPing + 100) { _rotTimeStamp = Time.time; if (Vector3.Distance(currentValue, serverValue) > 0.1f) { currentValue = serverValue; _rotationFrameHistory.Clear(); } } } break; case AuthoritativeFrameType.Scale: if (_scaLastFrame != serverFrame) { _scaLastFrame = serverFrame; _scaTimeStamp = Time.time; if (_scaleFrameHistory.Count > 0) { for (int i = _scaleFrameHistory.Count - 1; i >= 0; --i) { if (_scaleFrameHistory[i].Frame == serverFrame) { frameFound = true; iter = i; break; } } if (frameFound) { _scaleFrameHistory.RemoveRange(0, iter); _scaleFrameHistory[0].FrameActualValue = serverValue; _scaleFrameHistory[0].FrameValue = Vector3.zero; if (_scaleFrameHistory.Count > 1) { _scaleFrameHistory[1].FramePrevious = _scaleFrameHistory[0].FrameActualValue; _scaleFrameHistory[1].UpdateDelta(); } pos = serverValue; for (int i = 0; i < _scaleFrameHistory.Count; ++i) pos += _scaleFrameHistory[i].FrameValue; //Get the delta distance } } currentValue = pos; } else { if ((Time.time - _scaTimeStamp) * 1000 > owningNetworker.PreviousServerPing + 100) { _scaTimeStamp = Time.time; if (Vector3.Distance(currentValue, serverValue) > 0.1f) { currentValue = serverValue; _scaleFrameHistory.Clear(); } } } break; } return currentValue; }
/// <summary> /// Writes a <see cref="NetworkingStream"/> to a particular <see cref="NetWorker"/> /// </summary> /// <param name="socket">NetWorker(Socket) to write with</param> /// <param name="identifier">Unique identifier to be used</param> /// <param name="stream">The stream of data to be written</param> /// <param name="reliable">If this be a reliable UDP</param> public static void WriteUDP(NetWorker socket, string identifier, NetworkingStream stream, bool reliable = false) { socket.Write(identifier, stream, reliable); }