public void BroadcastUnreliable(MessageType messageType, MessageBase message) { var writer = new NetworkWriter(); writer.Write((byte)messageType); writer.Write(message); var buffer = writer.AsArray(); Parallel.ForEach(connections, connection => NetworkTransport.Send(HostID, connection, channels[QosType.Unreliable], buffer, buffer.Length, out var error)); }
void CmdFetchPlayerInfo() { PlayerInfoManager pim = GameObject.Find("PlayerInfoManager").GetComponent <PlayerInfoManager>(); PlayerInfo serverInfo = pim.getPlayerInfo(identity.connectionToClient); NetworkWriter writer = new NetworkWriter(); serverInfo.Serialize(writer); TargetSetPlayerInfo(identity.connectionToClient, writer.AsArray()); }
public void OnSyncButtonClick() { if (m_ConnectionEstablished) { m_Writer.SeekZero(); m_Writer.Write((int)Protocol.SyncArchive1); CustomStarUsage.m_Instance.Searialize(m_Writer); byte error; for (int i = 0; i < m_ConnectionIds.Count; ++i) { NetworkTransport.Send(m_HostId, m_ConnectionIds[i], 0, m_Writer.AsArray(), m_Writer.Position, out error); if ((NetworkError)error != NetworkError.Ok) { Debug.LogError("Failed to send message: " + (NetworkError)error); } } m_Writer.SeekZero(); m_Writer.Write((int)Protocol.SyncArchive2); Days.m_Instance.Searialize(m_Writer); for (int i = 0; i < m_ConnectionIds.Count; ++i) { NetworkTransport.Send(m_HostId, m_ConnectionIds[i], 0, m_Writer.AsArray(), m_Writer.Position, out error); if ((NetworkError)error != NetworkError.Ok) { Debug.LogError("Failed to send message: " + (NetworkError)error); } } m_Writer.SeekZero(); m_Writer.Write((int)Protocol.SyncArchive3); UseStarHistory.m_Instance.Searialize(m_Writer); for (int i = 0; i < m_ConnectionIds.Count; ++i) { NetworkTransport.Send(m_HostId, m_ConnectionIds[i], 0, m_Writer.AsArray(), m_Writer.Position, out error); if ((NetworkError)error != NetworkError.Ok) { Debug.LogError("Failed to send message: " + (NetworkError)error); } } } }
public static void Send(EMessageType type, MessageBase message, int hostId, int channelId, int connId) { // serialize the message, prepend the message type NetworkWriter writer = new NetworkWriter(); writer.Write((short)type); message.Serialize(writer); byte error; byte[] msgBytes = writer.AsArray(); NetworkTransport.Send(hostId, connId, channelId, msgBytes, msgBytes.Length * sizeof(char), out error); }
//Write the position and rotation to the data structure public virtual void Tick(ref RecordData data) { if (writer == null) { writer = new NetworkWriter(); } else { writer.SeekZero(); } writer.Write(transform.position); writer.Write(transform.rotation); data.bytes = writer.AsArray(); }
public static byte[] ToPack(out int size, params object[] datas) { NetworkWriter writer = new NetworkWriter(); byte dataCount = (byte)datas.Length; writer.Write(dataCount); foreach (object tempData in datas) { WriteData(writer, tempData); } size = writer.Position; return(writer.AsArray()); }
private void Send(ArraySegment <byte> packet, byte channel) { if (_network.PreprocessPacketToServer(packet)) { return; } var length = _network.CopyPacketToNetworkWriter(packet, _sendWriter); if (!NetworkManager.singleton.client.connection.SendBytes(_sendWriter.AsArray(), length, channel)) { Log.Error("Failed to send a message"); } }
public void SendUnreliable(MessageType messageType, MessageBase message, int id) { var writer = new NetworkWriter(); writer.Write((byte)messageType); writer.Write(message); var buffer = writer.AsArray(); NetworkTransport.Send(HostID, id, channels[QosType.Unreliable], buffer, buffer.Length, out var error); if ((NetworkError)error != NetworkError.Ok) { Debug.LogError($"{messageType} {(NetworkError)error}"); } }
public void Rpc(short index, short handle, byte[] bytes, int count) { Node player = index == 0 ? __client : __server; if (player == null) { return; } NetworkWriter writer = new NetworkWriter(); writer.Write(bytes, count); player.InvokeHandler(handle, -1, new NetworkReader(writer.AsArray())); }
public void Send(MessageType messageType, MessageBase message) { var writer = new NetworkWriter(); writer.Write((byte)messageType); writer.Write(message); var buffer = writer.AsArray(); NetworkTransport.Send(recHostId, ConnectionID, channels[QosType.Reliable], buffer, buffer.Length, out var error); if ((NetworkError)error != NetworkError.Ok) { Debug.LogError((NetworkError)error); } }
private bool Send(ArraySegment <byte> packet, byte channel) { if (_network.PreprocessPacketToServer(packet)) { return(true); } var length = _network.CopyPacketToNetworkWriter(packet, _sendWriter); if (!NetworkManager.singleton.client.connection.SendBytes(_sendWriter.AsArray(), length, channel)) { return(false); } return(true); }
public static void SendToAll(this IEnumerable <INetworkConnection> connections, byte header, MessageBase message, NetworkReliablity reliablity = NetworkReliablity.Reliable) { var writer = new NetworkWriter(); writer.Write(header); message.Serialize(writer); var bufferSize = writer.Position; var buffer = writer.AsArray(); foreach (var connection in connections) { connection.SendBytes(buffer, bufferSize, reliablity); } (message as IDisposable)?.Dispose(); }
public void OnServerAddPlayer(NetworkConnection conn, short playerControllerId, NetworkReader extraMessageReader) { LoginMessage login = new LoginMessage(); login.Deserialize(extraMessageReader); Debug.Log("playerControllerId = " + login.username + " with player id " + playerControllerId + " logged in!"); GameObject player = (GameObject)GameObject.Instantiate(playerPrefab); playerInfoManager.userLogin(login.username, player); NetworkWriter writer = new NetworkWriter(); serverMap.mapData.Serialize(writer); NetworkServer.AddPlayerForConnection(conn, player, playerControllerId); serverMap.TargetSetAndApplyMap(conn, writer.AsArray()); }
public void PlayerInput_serializes_and_deserializes_properly() { var sizes = new List <int>(); for (var i = 0; i < 1000; i++) { var state = InputUtility.RandomPlayerInput(); var networkWriter = new NetworkWriter(); state.Serialize(networkWriter); var bytes = networkWriter.AsArray(); sizes.Add(networkWriter.Position); var networkReader = new NetworkReader(bytes); var deserialized = PlayerInput.Deserialize(networkReader); Assert.AreEqual(state, deserialized); } Debug.Log($"Average Message Size: {sizes.Average()}"); }
private void Send(ArraySegment <byte> packet, HlapiConn connection, byte channel) { if (_network.PreprocessPacketToClient(packet, connection)) { return; } var length = _network.CopyPacketToNetworkWriter(packet, _sendWriter); if (connection.Connection == null) { Log.Error("Cannot send to a null destination"); } else if (!connection.Connection.SendBytes(_sendWriter.AsArray(), length, channel)) { Log.Error("Failed to send a message"); } }
public void MatchInput_serializes_and_deserializes_properly(int playerCount) { var sizes = new List <int>(); for (var i = 0; i < 1000; i++) { var input = InputUtility.RandomInput(playerCount); var networkWriter = new NetworkWriter(); var validMask = input.CreateValidMask(); input.Serialize(networkWriter, validMask); var bytes = networkWriter.AsArray(); sizes.Add(networkWriter.Position); var networkReader = new NetworkReader(bytes); var deserializedInput = MatchInput.Deserialize(networkReader, playerCount, validMask); Assert.AreEqual(input, deserializedInput); } Debug.Log($"Average Message Size ({playerCount}): {sizes.Average()}"); }
//public static void SendBitstreamToAllClients(ref UdpBitStream bitstream, short msgType, int channel = Channels.DefaultUnreliable) //{ // reusablewriter.StartMessage(msgType); // reusablewriter.WriteUncountedByteArray(bitstream.Data, bitstream.BytesUsed); // reusablewriter.FinishMessage(); // //reusablewriter.SendPayloadArrayToAllClients(msgType); // foreach (NetworkConnection nc in NetworkServer.connections) // { // if (nc == null) // continue; // nc.SendWriter(reusablewriter, channel); // } //} public static void SendPayloadArrayToAllClients(this NetworkWriter writer, short msgType, int channel = Channels.DefaultUnreliable) { reusablewriter.StartMessage(msgType); for (int i = 4; i < writer.Position; i++) { reusablewriter.Write(writer.AsArray()[i]); } reusablewriter.FinishMessage(); foreach (NetworkConnection nc in NetworkServer.connections) { if (nc == null) { continue; } nc.SendWriter(reusablewriter, channel); } }
public void Rpc(short index, short handle, MessageBase message) { Node player = index == 0 ? __client : __server; if (player == null) { return; } NetworkWriter writer = new NetworkWriter(); writer.Write(handle); if (message != null) { writer.Write(message); } player.InvokeHandler(handle, -1, new NetworkReader(writer.AsArray())); }
//Write the position and rotation to the data structure public virtual void Tick(ref RecordData data) { if (writer == null) { writer = new NetworkWriter(); } else #if ENABLE_MIRROR { writer.Position = 0; } #else { writer.SeekZero(); } #endif writer.Write(transform.position); writer.Write(transform.rotation); #if ENABLE_MIRROR data.bytes = writer.ToArray(); #else data.bytes = writer.AsArray(); #endif }
protected override void OnEnterScope() { IsPaused = false; // right after entering the scope, send out all queued signals while (_signalQueueEnabled && queuedSignalWriters.Count > 0) { NetworkWriter writer = queuedSignalWriters.Dequeue(); // modify the 2nd and 3rd bytes in the array containing the possibly incorrect msgType byte[] writerBytes = writer.AsArray(); byte[] msgTypeBytes = BitConverter.GetBytes(msgType); // replace the bytes within the internal array Buffer.BlockCopy(msgTypeBytes, 0, writerBytes, 2, sizeof(short)); ((INetworkSender)this).PrepareAndSendWriter(writer); } base.OnEnterScope(); }
public static void SendNetworkWriter <TPeer>(NetworkWriter writer, IEnumerable <TPeer> peers) where TPeer : NetworkPeer { byte error; byte[] bufferData = writer.AsArray(); short bufferSize = writer.Position; foreach (TPeer peer in peers) { if (!peer.isConnected) { return; } NetworkTransport.Send(peer.hostId, peer.connectionId, UNRELIABLE_SEQUENCED_CHANNEL, bufferData, bufferSize, out error); NetworkError nerror = (NetworkError)error; if (nerror != NetworkError.Ok) { Debug.LogError("Network error: " + nerror); } } }
public byte GetCommandChecksum(Inputs inp) { #if (CMD_CHECKSUM) if (cSumWriter == null) { cSumWriter = new NetworkWriter(); } GetCommandChecksum(inp, cSumWriter); sumBytes = cSumWriter.AsArray(); int checkSum = 0; for (int i = 0; i < sumBytes.Length; i++) { checkSum += sumBytes[i]; } return((byte)(checkSum & 0xFF)); #else return(0); #endif }
private void checkIfPickedUp() { if (!isServer) { return; } GameObject[] players = GameObject.FindGameObjectsWithTag("Player"); foreach (GameObject player in players) { MoleController playerController = player.GetComponent <MoleController> (); if (playerController == null || playerController.gamePos == null) { continue; } float heightDiff = Mathf.Abs(gamePos.depth - playerController.gamePos.depth); float planeDiff = (gamePos.planePosition - playerController.gamePos.planePosition).magnitude; if (heightDiff < HEIGHT_CUTOFF && planeDiff < PICK_UP_DISTANCE) { Player p = player.GetComponent <Player> (); Debug.Log(getItem() + " getting picked up of quantity " + quantity); InventoryOperation invOp = new InventoryOperation(InventoryOperation.Operation.AddItems, new byte[][] { itemData.data, System.Text.Encoding.Default.GetBytes(quantity.ToString()) }); int remainder = player.GetComponent <Player> ().PerformInventoryAction(invOp, "general"); Debug.Log("remainder: " + remainder); if (remainder >= quantity) { return; } quantity = remainder; if (!player.GetComponent <NetworkIdentity> ().isLocalPlayer) { //player.GetComponent<Player> ().beltUI.updateUI (); //} else { NetworkWriter writer = new NetworkWriter(); invOp.Serialize(writer); p.TargetPerformInventoryAction(player.GetComponent <NetworkIdentity> ().connectionToClient, writer.AsArray(), "general"); //p.TargetPickUpItem (player.GetComponent<NetworkIdentity> ().connectionToClient, getItem().Encode ()); } if (quantity <= 0) { NetworkServer.Destroy(gameObject); } } } }
public override bool SendWriter(NetworkWriter writer, int channelId) { m_LocalClient.InvokeBytesOnClient(writer.AsArray(), channelId); return(true); }
private void __OnRegistered(Network.Node player) { if (player == null) { return; } short index = player.index; player.RegisterHandler((short)HostMessageHandle.Ready, delegate(NetworkReader reader) { Ready(index); }); player.RegisterHandler((short)HostMessageHandle.NotReady, delegate(NetworkReader reader) { NotReady(index); }); Node node; if (GetNode(player.index, out node)) { IEnumerable <KeyValuePair <int, Network.Node> > room = GetRoom(node.roomIndex); if (room != null) { NetworkWriter writer = new NetworkWriter(); writer.Write((short)HostMessageHandle.Ready); writer.Write(new ReadyMessage()); HostMessage hostMessage = new HostMessage(-1, writer.Position, writer.AsArray()); Lobby.Node instance; int i; foreach (KeyValuePair <int, Network.Node> pair in room) { instance = pair.Value as Lobby.Node; if (instance != null) { hostMessage.index = instance.index; for (i = 0; i < instance._count; ++i) { Send(node.connectionId, (short)Network.HostMessageType.Rpc, hostMessage); } } } IEnumerable <int> neighborRoomIndices = GetNeighborRoomIndices(node.roomIndex); if (neighborRoomIndices != null) { foreach (int neighborRoomIndex in neighborRoomIndices) { room = GetRoom(neighborRoomIndex); if (room == null) { continue; } foreach (KeyValuePair <int, Network.Node> pair in room) { instance = pair.Value as Lobby.Node; if (instance != null) { hostMessage.index = instance.index; for (i = 0; i < instance._count; ++i) { Send(node.connectionId, (short)Network.HostMessageType.Rpc, hostMessage); } } } } } } } }
protected override bool _Unregister(NetworkReader reader, int connectionId, short index) { int count = 0; while (__NotReady(index, connectionId >= 0)) { ++count; } if (connectionId >= 0 && count > 0) { Node node; if (GetNode(index, out node)) { IEnumerable <KeyValuePair <int, Network.Node> > room = GetRoom(node.roomIndex); if (room != null) { NetworkWriter writer = new NetworkWriter(); writer.Write((short)HostMessageHandle.NotReady); writer.Write(new NotReadyMessage()); HostMessage hostMessage = new HostMessage(-1, writer.Position, writer.AsArray()); Lobby.Node instance; int i; foreach (KeyValuePair <int, Network.Node> pair in room) { instance = pair.Value as Lobby.Node; if (instance != null) { hostMessage.index = instance.index; for (i = 0; i < instance._count; ++i) { Send(connectionId, (short)Network.HostMessageType.Rpc, hostMessage); } } } IEnumerable <int> neighborRoomIndices = GetNeighborRoomIndices(node.roomIndex); if (neighborRoomIndices != null) { foreach (int neighborRoomIndex in neighborRoomIndices) { room = GetRoom(neighborRoomIndex); if (room == null) { continue; } foreach (KeyValuePair <int, Network.Node> pair in room) { instance = pair.Value as Lobby.Node; if (instance != null) { hostMessage.index = instance.index; for (i = 0; i < instance._count; ++i) { Send(connectionId, (short)Network.HostMessageType.Rpc, hostMessage); } } } } } } } } return(true); }
public void Rpc(short index, short handle, MessageBase message) { NetworkConnection connection = __client == null ? null : __client.connection; if (connection == null) { return; } NetworkWriter writer = __GetWriter(); writer.Write(handle); writer.Write(message); connection.Send((short)HostMessageType.Rpc, __GetMessage(index, writer.Position, writer.AsArray())); }
void OnGUI() { if (string.IsNullOrEmpty(Application.cloudProjectId)) { GUILayout.Label("You must set up the project first. See the Multiplayer tab in the Service Window"); } else { GUILayout.Label("Cloud Project ID: " + Application.cloudProjectId); } if (m_MatchJoined) { GUILayout.Label("Match joined '" + m_MatchName + "' on Matchmaker server"); } else if (m_MatchCreated) { GUILayout.Label("Match '" + m_MatchName + "' created on Matchmaker server"); } GUILayout.Label("Connection Established: " + m_ConnectionEstablished); if (m_MatchCreated || m_MatchJoined) { GUILayout.Label("Relay Server: " + m_MatchInfo.address + ":" + m_MatchInfo.port); GUILayout.Label("NetworkID: " + m_MatchInfo.networkId + " NodeID: " + m_MatchInfo.nodeId); GUILayout.BeginHorizontal(); GUILayout.Label("Outgoing message:"); m_NetworkMessage = GUILayout.TextField(m_NetworkMessage); GUILayout.EndHorizontal(); GUILayout.Label("Last incoming message: " + m_LastReceivedMessage); if (m_ConnectionEstablished && GUILayout.Button("Send message")) { m_Writer.SeekZero(); m_Writer.Write(m_NetworkMessage); byte error; for (int i = 0; i < m_ConnectionIds.Count; ++i) { NetworkTransport.Send(m_HostId, m_ConnectionIds[i], 0, m_Writer.AsArray(), m_Writer.Position, out error); if ((NetworkError)error != NetworkError.Ok) { Debug.LogError("Failed to send message: " + (NetworkError)error); } } } if (GUILayout.Button("Shutdown")) { m_NetworkMatch.DropConnection(m_MatchInfo.networkId, m_MatchInfo.nodeId, 0, OnConnectionDropped); } } else { if (GUILayout.Button("Create Room")) { m_NetworkMatch.CreateMatch(m_MatchName, 4, true, "", "", "", 0, 0, OnMatchCreate); } if (GUILayout.Button("Join first found match")) { m_NetworkMatch.ListMatches(0, 1, "", true, 0, 0, (success, info, matches) => { if (success && matches.Count > 0) { m_NetworkMatch.JoinMatch(matches[0].networkId, "", "", "", 0, 0, OnMatchJoined); } }); } if (GUILayout.Button("List rooms")) { m_NetworkMatch.ListMatches(0, 20, "", true, 0, 0, OnMatchList); } if (m_MatchList.Count > 0) { GUILayout.Label("Current rooms:"); } foreach (var match in m_MatchList) { if (GUILayout.Button(match.name)) { m_NetworkMatch.JoinMatch(match.networkId, "", "", "", 0, 0, OnMatchJoined); } } } }
public override bool SendWriter(NetworkWriter writer, int channelId) { return(m_LocalServer.InvokeBytes(this, writer.AsArray(), (short)writer.AsArray().Length, channelId)); }
public override bool SendWriter(NetworkWriter writer, int channelId) { this.m_LocalClient.InvokeBytesOnClient(writer.AsArray(), channelId); return true; }
// Update is called once per frame void Update() { this.timeSinceSent += Time.deltaTime; this.timeSinceReceived += Time.deltaTime; if (this.isServer) { if (this.timeSinceSent >= 1.0f / this.sendRate) { // we should send update // order of data: position, rotation, velocity, angular velocity byte bitField = 3; NetworkWriter w = new NetworkWriter(); w.Write(transform.position); w.Write(transform.rotation.eulerAngles); if (this.syncRigidBodyVelocity && this.rigidBody != null) { w.Write(this.rigidBody.velocity); bitField |= 4; } if (this.syncRigidBodyAngularVelocity && this.rigidBody != null) { w.Write(this.rigidBody.angularVelocity); bitField |= 8; } if (0 == this.channel) { this.RpcSendingUpdateChannel0(bitField, w.AsArray()); } else if (1 == this.channel) { this.RpcSendingUpdateChannel1(bitField, w.AsArray()); } else if (2 == this.channel) { this.RpcSendingUpdateChannel2(bitField, w.AsArray()); } this.timeSinceSent = 0; } } else if (this.isClient) { // lerp positon and rotation // float lerp = 1.0f / Mathf.Pow (this.lerpMovementFactor, Time.deltaTime); // transform.position = Vector3.Lerp( transform.position, syncPosition, lerp); // transform.position += this.rigidBody.velocity * Time.deltaTime; // Vector3 difference = syncPosition - transform.position; // Vector3 difference = syncPosition + this.rigidBody.velocity * 1.0f / this.sendRate - transform.position ; // float timeLeftToNextUpdate = Mathf.Clamp (1.0f / this.sendRate - this.timeSinceReceived, 0.0001f, Mathf.Infinity); // transform.position += difference * Mathf.Clamp (Time.deltaTime / timeLeftToNextUpdate, 0, 1); float timePassed = Time.unscaledTime - this.timeWhenLastFrameArrived; float lerp = 1; //timePassed / (1.0f / this.sendRate); // transform.position = Vector3.Lerp( syncSourcePosition, syncPosition, lerp ); // transform.rotation = Quaternion.Lerp( Quaternion.Euler( syncSourceRotation ), Quaternion.Euler( syncRotation ), lerp ); /* Vector3 difference = Vector3.zero; * if (frames.Count > 0) { * * difference = frames [0].position - transform.position; * if (difference.sqrMagnitude >= 0.0001f) { * // we haven't arrived at destination * * /* // how much time has passed since the first frame * float timeLate = Time.unscaledTime - frames [0].timeWhenArrived; * // how much time we have left to move to new position * float timeLeft = Mathf.Clamp (1.0f / sendRate - timeLate, 0, Mathf.Infinity) * 3; * int numFramesLeft = Mathf.RoundToInt (timeLeft / Time.smoothDeltaTime); * float lerp = 1; * if (numFramesLeft != 0) * lerp = 1.0f / (numFramesLeft + 1); * // float lerp = Time.smoothDeltaTime / (1.0f / sendRate) ; * transform.position = Vector3.Lerp (transform.position, frames [0].position, lerp); * // end of comment here * * // float move = frames [0].velocity.magnitude * Time.deltaTime * this.lerpMovementFactor; * // if (move * move > difference.sqrMagnitude) * // move = difference.magnitude; * // transform.position += difference.normalized * move; * * // transform.position = frames [0].position; * * difference = frames [0].position - transform.position; * } * * * // lerp = 1.0f / Mathf.Pow (this.lerpRotationFactor, Time.deltaTime); * // transform.rotation = Quaternion.Lerp( transform.rotation, Quaternion.Euler(syncRotation), lerp); * * // transform.rotation = Quaternion.Euler (syncRotation); * * transform.rotation = Quaternion.Lerp (transform.rotation, Quaternion.Euler (frames [0].eulers), this.lerpRotationFactor); * * * if (difference.sqrMagnitude < 0.0001f) { * // we arrived at destination position * * // remove this frame from list * frames.RemoveAt (0); * } * } */ // transform.rotation = Quaternion.Euler( syncRotation ); } }
public override bool SendWriter(NetworkWriter writer, int channelId) { return this.m_LocalServer.InvokeBytes(this, writer.AsArray(), (int) (short) writer.AsArray().Length, channelId); }