示例#1
0
        public BMSByte Receive(ref IPEndPoint remoteEP, ref string endpoint)
        {
            CheckDisposed();

            recBuffer.Clear();

            if (endPoint == null)
            {
                endPoint = new IPEndPoint(IPAddress.Any, 0);
            }

            int dataRead = socket.ReceiveFrom(recBuffer.byteArr, ref endPoint);


            if (!connections.ContainsKey(endPoint))
            {
                connections.Add(endPoint, (((IPEndPoint)endPoint).Address.ToString() + HOST_PORT_CHARACTER_SEPARATOR + ((IPEndPoint)endPoint).Port.ToString()));
                BeardedManStudios.Forge.Logging.BMSLog.Log("endpoint added to connections: " + ((IPEndPoint)endPoint).Address.ToString());
            }

            endpoint = connections[endPoint];

            //if (dataRead < recBuffer.Size)
            //	recBuffer = CutArray(recBuffer, dataRead);

            recBuffer.SetSize(dataRead);

            remoteEP = (IPEndPoint)endPoint;

            return(recBuffer);
        }
示例#2
0
        /// <summary>
        /// Instantiate an instance of Player
        /// </summary>
        /// <returns>
        /// A local instance of PlayerBehavior
        /// </returns>
        /// <param name="index">The index of the Player prefab in the NetworkManager to Instantiate</param>
        /// <param name="position">Optional parameter which defines the position of the created GameObject</param>
        /// <param name="rotation">Optional parameter which defines the rotation of the created GameObject</param>
        /// <param name="sendTransform">Optional Parameter to send transform data to other connected clients on Instantiation</param>
        public PlayerBehavior InstantiatePlayer(int index          = 0, Vector3?position = null, Quaternion?rotation = null,
                                                bool sendTransform = true)
        {
            if (PlayerNetworkObject.Length <= index)
            {
                Debug.Log("Prefab(s) missing for: Player. Add them at the NetworkManager prefab.");
                return(null);
            }

            var go          = Instantiate(PlayerNetworkObject[index]);
            var netBehavior = go.GetComponent <PlayerBehavior>();

            NetworkObject obj = null;

            if (!sendTransform && position == null && rotation == null)
            {
                obj = netBehavior.CreateNetworkObject(Networker, index);
            }
            else
            {
                metadata.Clear();

                if (position == null && rotation == null)
                {
                    byte transformFlags = 0x1 | 0x2;
                    ObjectMapper.Instance.MapBytes(metadata, transformFlags);
                    ObjectMapper.Instance.MapBytes(metadata, go.transform.position, go.transform.rotation);
                }
                else
                {
                    byte transformFlags = 0x0;
                    transformFlags |= (byte)(position != null ? 0x1 : 0x0);
                    transformFlags |= (byte)(rotation != null ? 0x2 : 0x0);
                    ObjectMapper.Instance.MapBytes(metadata, transformFlags);

                    if (position != null)
                    {
                        ObjectMapper.Instance.MapBytes(metadata, position.Value);
                    }

                    if (rotation != null)
                    {
                        ObjectMapper.Instance.MapBytes(metadata, rotation.Value);
                    }
                }

                obj = netBehavior.CreateNetworkObject(Networker, index, metadata.CompressBytes());
            }

            go.GetComponent <PlayerBehavior>().networkObject = (PlayerNetworkObject)obj;

            FinalizeInitialization(go, netBehavior, obj, position, rotation, sendTransform);

            return(netBehavior);
        }
示例#3
0
        public GameBehavior InstantiateGame(int index = 0, Vector3?position = null, Quaternion?rotation = null, bool sendTransform = true)
        {
            var go          = Instantiate(GameNetworkObject[index]);
            var netBehavior = go.GetComponent <GameBehavior>();

            NetworkObject obj = null;

            if (!sendTransform && position == null && rotation == null)
            {
                obj = netBehavior.CreateNetworkObject(Networker, index);
            }
            else
            {
                metadata.Clear();

                if (position == null && rotation == null)
                {
                    metadata.Clear();
                    byte transformFlags = 0x1 | 0x2;
                    ObjectMapper.Instance.MapBytes(metadata, transformFlags);
                    ObjectMapper.Instance.MapBytes(metadata, go.transform.position, go.transform.rotation);
                }
                else
                {
                    byte transformFlags = 0x0;
                    transformFlags |= (byte)(position != null ? 0x1 : 0x0);
                    transformFlags |= (byte)(rotation != null ? 0x2 : 0x0);
                    ObjectMapper.Instance.MapBytes(metadata, transformFlags);

                    if (position != null)
                    {
                        ObjectMapper.Instance.MapBytes(metadata, position.Value);
                    }

                    if (rotation != null)
                    {
                        ObjectMapper.Instance.MapBytes(metadata, rotation.Value);
                    }
                }

                obj = netBehavior.CreateNetworkObject(Networker, index, metadata.CompressBytes());
            }

            go.GetComponent <GameBehavior>().networkObject = (GameNetworkObject)obj;

            FinalizeInitialization(go, netBehavior, obj, position, rotation, sendTransform);

            return(netBehavior);
        }
示例#4
0
        /// <summary>
        /// Check for and return any packets sent to us
        /// </summary>
        /// <param name="from">SteamId of the player who sent us this packet</param>
        /// <returns>Packet in BMSByte format</returns>
        public BMSByte Receive(out SteamId from)
        {
            CheckDisposed();

            if (!SteamNetworking.IsP2PPacketAvailable())
            {
                from = default;
                return(null);
            }

            recBuffer.Clear();

            var packet = SteamNetworking.ReadP2PPacket();

            if (packet.HasValue)
            {
                from = packet.Value.SteamId;
                recBuffer.SetSize(packet.Value.Data.Length);
                recBuffer.byteArr = packet.Value.Data;
                return(recBuffer);
            }

            from = default;
            return(null);
        }
        public BMSByte Receive(ref IPEndPoint remoteEP, ref string endpoint)
        {
            CheckDisposed();

            recBuffer.Clear();

            if (endPoint == null)
            {
                endPoint = new IPEndPoint(IPAddress.Any, 0);
            }

            // 将数据报接收到数据缓冲区并存储终结点。
            // buffer Byte 类型的数组,它是存储接收到的数据的位置。
            // remoteEP 按引用传递的 EndPoint,表示远程服务器。
            // 返回值 接收到的字节数。
            int dataRead = socket.ReceiveFrom(recBuffer.byteArr, ref endPoint);

            if (!connections.ContainsKey(endPoint))
            {
                connections.Add(endPoint, (((IPEndPoint)endPoint).Address.ToString() + HOST_PORT_CHARACTER_SEPARATOR + ((IPEndPoint)endPoint).Port.ToString()));
            }

            endpoint = connections[endPoint];

            //if (dataRead < recBuffer.Size)
            //	recBuffer = CutArray(recBuffer, dataRead);

            recBuffer.SetSize(dataRead);

            remoteEP = (IPEndPoint)endPoint;
            return(recBuffer);
        }
示例#6
0
        public int Receive(BMSByte buffer, ref EndPoint endpoint)
        {
            buffer.Clear();
            int length = _socket.ReceiveFrom(buffer.byteArr, 0, buffer.byteArr.Length, SocketFlags.None, ref endpoint);

            buffer.AugmentSize(length);
            return(length);
        }
示例#7
0
        /// <summary>
        /// Collect all of the data from all of the packets in this sequence and return it
        /// </summary>
        /// <returns>The complete packet sequence data</returns>
        public BMSByte GetData()
        {
            data.Clear();

            for (int i = 0; i < End; i++)
            {
                data.BlockCopy(packets[i].rawBytes, 0, packets[i].rawBytes.Length);
            }

            return(data);
        }
        public virtual NetworkBehavior InstantiateNetworkBehavior(int pCreateCode = -1, IRPCSerializable pBehaviorData = null, Vector3?pPosition = null, Quaternion?pRotation = null, bool pSendTransform = true)
        {
            GameObject prefab = _networkBehaviorListSO.behaviorList.GetByCreateCode(pCreateCode);

            if (prefab == null)
            {
                return(null);
            }

            var           go          = Instantiate(prefab);
            var           netBehavior = go.GetComponent <NetworkBehavior>();
            NetworkObject obj         = null;

            if (!pSendTransform && pPosition == null && pRotation == null)
            {
                obj = netBehavior.CreateNetworkObject(_networker, pCreateCode);
            }
            else
            {
                _tmpMetadata.Clear();
                if (pPosition == null && pRotation == null)
                {
                    byte transformFlags = 0x1 | 0x2;
                    ObjectMapper.Instance.MapBytes(_tmpMetadata, transformFlags);
                    ObjectMapper.Instance.MapBytes(_tmpMetadata, go.transform.position, go.transform.rotation);
                }
                else
                {
                    byte transformFlags = 0x0;
                    transformFlags |= (byte)(pPosition != null ? 0x1 : 0x0);
                    transformFlags |= (byte)(pRotation != null ? 0x2 : 0x0);
                    ObjectMapper.Instance.MapBytes(_tmpMetadata, transformFlags);

                    if (pPosition != null)
                    {
                        ObjectMapper.Instance.MapBytes(_tmpMetadata, pPosition.Value);
                    }

                    if (pRotation != null)
                    {
                        ObjectMapper.Instance.MapBytes(_tmpMetadata, pRotation.Value);
                    }
                }

                obj = netBehavior.CreateNetworkObject(_networker, pCreateCode, _tmpMetadata.CompressBytes());
            }

            SetINetworkSceneObject(netBehavior, obj);
            SetIRPCSerializable(netBehavior, pBehaviorData);
            FinalizeInitialization(go, netBehavior, obj, pPosition, pRotation, pSendTransform);
            return(netBehavior);
        }
		public BMSByte Receive(uint msgSize, out CSteamID from)
		{
            uint dataRead = 0;
			CheckDisposed();

			recBuffer.Clear();
            recBuffer.SetSize((int)msgSize);


            if(SteamNetworking.ReadP2PPacket(recBuffer.byteArr, msgSize, out dataRead, out from))
            {
                return recBuffer;
            }

            return null;
		}
示例#10
0
        protected void ReadNetwork()
        {
            EndPoint readEp = new IPEndPoint(IPAddress.Parse(CommonSocketBase.LOCAL_IPV4), 0);
            var      buffer = new BMSByte();

            buffer.SetArraySize(2048);
            try
            {
                while (true)
                {
                    CancellationSource.Token.ThrowIfCancellationRequested();
                    buffer.Clear();
                    ManagedSocket.Receive(buffer, ref readEp);
                    ProcessMessageRead(buffer, readEp);
                }
            }
            catch (OperationCanceledException) { }
        }
        /// <summary>
        /// Check for and return any packets sent to us
        /// </summary>
        /// <param name="from">SteamId of the player who sent us this packet</param>
        /// <returns>Packet in BMSByte format</returns>
        public BMSByte Receive(out SteamId from)
        {
            CheckDisposed();

            recBuffer.Clear();

            var packet = SteamNetworking.ReadP2PPacket();

            if (packet.HasValue)
            {
                from = packet.Value.SteamId;
                recBuffer.SetSize(packet.Value.Data.Length);
                recBuffer.byteArr = packet.Value.Data;
                //Logging.BMSLog.Log("packet received from " + from.Value.ToString() + ". Length = " + packet.Value.Data.Length);
                return(recBuffer);
            }

            from = default(SteamId);
            return(null);
        }
示例#12
0
        public BMSByte Receive(ref IPEndPoint remoteEP)
        {
            CheckDisposed();

            recBuffer.Clear();

            if (endPoint == null)
            {
                endPoint = new IPEndPoint(IPAddress.Any, 0);
            }

            int dataRead = socket.ReceiveFrom(recBuffer.byteArr, ref endPoint);

            if (!connections.ContainsKey(endPoint))
            {
                connections.Add(endPoint, (((IPEndPoint)endPoint).Address.ToString() + HOST_PORT_CHARACTER_SEPARATOR + ((IPEndPoint)endPoint).Port.ToString()));
            }

            recBuffer.SetSize(dataRead);

            remoteEP = (IPEndPoint)endPoint;
            return(recBuffer);
        }
示例#13
0
    public override void SendInputBuffer(RpcArgs args)
    {
        lock (_ServerInputQueue)
        {
            uint seq = args.GetNext <uint>();
            if (seq > _LastSequence)
            {
                //our unreliable input has arrived it will contain multiple inputs
                _UnreliableInputBytesRecv.Clear();
                _UnreliableInputBytesRecv.Append(args.GetNext <byte[]>());
                _LastSequence = seq;
                //they should be stored oldest to newest, with newest being the last input collected
                for (int i = 0; i < _UnreliableInputBuffer.Length; i++)
                {
                    ulong   timestep = UnityObjectMapper.Instance.Map <ulong>(_UnreliableInputBytesRecv);
                    Vector3 velocity = UnityObjectMapper.Instance.Map <Vector3>(_UnreliableInputBytesRecv);

                    Quaternion rotation = UnityObjectMapper.Instance.Map <Quaternion>(_UnreliableInputBytesRecv);

                    if (timestep > _LastInputHandled)
                    {
                        _ServerInputQueue.Enqueue(new InputCommand()
                        {
                            Time     = timestep,
                            Velocity = velocity,
                            Rotation = rotation
                        });
                        _LastInputHandled = timestep;
                    }
                }
            }
            else
            {
                Debug.LogFormat("OOS: {0} {1}", _LastSequence, seq);
            }
        }
    }
示例#14
0
        public BMSByte Receive(ref IPEndPoint remoteEP, ref string endpoint)
        {
            try
            {
                CheckDisposed();
                recBuffer.Clear();

                if (endPoint == null)
                {
                    endPoint = new IPEndPoint(IPAddress.Any, 0);
                }

                int dataRead = socket.ReceiveFrom(recBuffer.byteArr, ref endPoint);

                if (!connections.ContainsKey(endPoint))
                {
                    connections.Add(endPoint, (((IPEndPoint)endPoint).Address.ToString() + HOST_PORT_CHARACTER_SEPARATOR + ((IPEndPoint)endPoint).Port.ToString()));
                }

                endpoint = connections[endPoint];

                //if (dataRead < recBuffer.Size)
                //	recBuffer = CutArray(recBuffer, dataRead);

                recBuffer.SetSize(dataRead);

                remoteEP = (IPEndPoint)endPoint;
                return(recBuffer);
            }
            catch (SocketException)
            {
                // It would not be uncommon for a socket-exception to occur in the call to socket.ReceiveFrom.
                // This should not necessarily lead to concerns.
                //throw;
                return(recBuffer);
            }
        }
示例#15
0
    private void SendInput(ulong timestep, Vector3 velocity, Quaternion rotation)
    {
        UnityEngine.Profiling.Profiler.BeginSample("SendInput");
#if USE_UNRELIABLE_INPUT
        //add the most recent input to the write index
        _UnreliableInputBuffer[_UnreliableInputBufferWriteIndex].Time     = timestep;
        _UnreliableInputBuffer[_UnreliableInputBufferWriteIndex].Velocity = velocity;
        _UnreliableInputBuffer[_UnreliableInputBufferWriteIndex].Rotation = rotation;
        _UnreliableInputBytesSend.Clear();

        //since we always send the full array we can kind of exploit it, and know that writeindex + 1 is the oldest in the list
        //then just step forward again the full size and we will be back on the value we just wrote, adding it last
        int idx = (_UnreliableInputBufferWriteIndex + 1) % _UnreliableInputBuffer.Length;
        for (int i = 0; i < _UnreliableInputBuffer.Length; i++)
        {
            //we want to send the oldest first so when we check on the server we can just iterate through the args
            var input = _UnreliableInputBuffer[idx];

            UnityEngine.Profiling.Profiler.BeginSample("Mapping");
            UnityObjectMapper.Instance.MapBytes(_UnreliableInputBytesSend, input.Time);
            UnityObjectMapper.Instance.MapBytes(_UnreliableInputBytesSend, input.Velocity);
            UnityObjectMapper.Instance.MapBytes(_UnreliableInputBytesSend, input.Rotation);
            UnityEngine.Profiling.Profiler.EndSample();

            idx = (idx + 1) % _UnreliableInputBuffer.Length;
        }
        _UnreliableInputBufferWriteIndex = (_UnreliableInputBufferWriteIndex + 1) % _UnreliableInputBuffer.Length;

        UnityEngine.Profiling.Profiler.BeginSample("SendRPC");
        networkObject.SendRpcUnreliable(RPC_SEND_INPUT_BUFFER, Receivers.Server, _Sequence++, _UnreliableInputBytesSend.byteArr);
        UnityEngine.Profiling.Profiler.EndSample();
#else
        networkObject.SendRpc(RPC_SEND_INPUTS, Receivers.Server, timestep, velocity, rotation);
#endif
        UnityEngine.Profiling.Profiler.EndSample();
    }
 private BMSByte ServerSerialze(int num)
 {
     cachedData.Clear();
     return(ObjectMapper.MapBytes(cachedData, "hello world from the server - " + num));
 }
		private async void ConnectionReceived(StreamSocketListener sender, StreamSocketListenerConnectionReceivedEventArgs args)
		{
			BMSByte tmp = new BMSByte();

			if (Connections >= MaxConnections)
			{
				ObjectMapper.MapBytes(tmp, "Max Players Reached On Server");

				WriteAndClose(args.Socket, new NetworkingStream(Networking.ProtocolType.TCP).Prepare(this,
					NetworkingStream.IdentifierType.Disconnect, null, tmp));
				
				return;
			}

			// TODO:  Setup name
			string name = string.Empty;

			NetworkingPlayer player = new NetworkingPlayer(ServerPlayerCounter, args.Socket.Information.RemoteAddress.CanonicalName, args.Socket, name);
			Players.Add(player);
			OnPlayerConnected(player);

			tmp.Clear();
			ObjectMapper.MapBytes(tmp, player.NetworkId);

			Write(player, new NetworkingStream(Networking.ProtocolType.TCP).Prepare(this,
				NetworkingStream.IdentifierType.Player, null, tmp));
		}
示例#18
0
        /// <summary>
        /// Creates the frame data using the passed in payload
        /// </summary>
        private void CreateFrame(bool useMask, ulong timestep, byte[] payload, Receivers receivers, int groupId, byte routerId, bool isStream)
        {
            // If we are to use a mask then generate a random mask
            if (useMask)
            {
                mask = new byte[4];
                new Random().NextBytes(mask);
            }

            StreamData = new BMSByte();

            TimeStep  = timestep;
            GroupId   = groupId;
            RouterId  = routerId;
            Receivers = receivers;
            UniqueId  = UniqueMessageIdCounter++;

            // Generate the frame identity
            byte[] frame = new byte[10];

            // The first byte of the data is always the control byte, which dictates the message type
            frame[0] = ControlByte;

            int length = payload.Length;

            if (isStream)
            {
                length += 21;                  // Group id (4), receivers (1), time step (8), unique id (8)
            }
            else
            {
                length += 16; // time step (8), unique id (8)
            }
            if (frame[0] == Binary.CONTROL_BYTE)
            {
                length += 1;
            }

            // Determine the length of the payload
            int dataStartIndex = 0;

            if (length <= 125)
            {
                frame[1]       = (byte)(useMask ? length | 128 : length);
                dataStartIndex = 2;
            }
            else if (length >= 126 && length <= 65535)
            {
                dataStartIndex = 4;
                frame[1]       = (byte)(useMask ? 254 : 126);
            }
            else
            {
                dataStartIndex = 10;
                frame[1]       = (byte)(useMask ? 255 : 127);
            }

            // If the payload is greater than a byte (255) then set the order of the bytes for the length
            if (dataStartIndex > 2)
            {
                int i = 0, j = 2, largestBitIndex = (dataStartIndex - 3) * 8;

                // Little endian / Big endian reversal based on mask
                //if (mask.Length == 0)
                //{
                for (i = largestBitIndex; i >= 0; i -= 8)
                {
                    frame[j++] = (byte)((((long)length) >> i) & 255);
                }
                //} else
                //{
                //    for (i = 0; i <= largestBitIndex; i += 8)
                //        frame[j++] = (byte)((payload.Length >> i) & 255);
                //}
            }

            // Prepare the stream data with the size so that it doesn't have to keep resizing
            StreamData.SetSize(dataStartIndex + mask.Length + length);
            StreamData.Clear();

            // Add the frame bytes
            StreamData.BlockCopy(frame, 0, dataStartIndex);

            // Add the mask bytes
            StreamData.BlockCopy(mask, 0, mask.Length);

            // Setup the int that tracks where the payload begins
            payloadStart = dataStartIndex + mask.Length;

            // If we are on a stream then use groupId
            if (isStream)
            {
                StreamData.BlockCopy(BitConverter.GetBytes(groupId), 0, sizeof(int));
                payloadStart += sizeof(int);
            }

            // Copy the routerId if this is a binary frame
            if (frame[0] == Binary.CONTROL_BYTE)
            {
                StreamData.BlockCopy(new byte[1] {
                    routerId
                }, 0, sizeof(byte));
                payloadStart += 1;
            }

            // Add the initial payload bytes
            StreamData.BlockCopy(payload, 0, payload.Length);

            if (isStream)
            {
                StreamData.BlockCopy(new byte[1] {
                    (byte)Receivers
                }, 0, sizeof(byte));
            }

            // Add the time step to the end of the frame
            StreamData.BlockCopy <ulong>(TimeStep, sizeof(ulong));

            // Add the unique message id for this frame just before the timestep frame
            StreamData.BlockCopy <ulong>(UniqueId, sizeof(ulong));

            if (mask.Length > 0)
            {
                for (int i = dataStartIndex + mask.Length, j = 0; i < StreamData.Size; i++, j++)
                {
                    StreamData.byteArr[i] = (byte)(StreamData.byteArr[i] ^ mask[j % 4]);
                }
            }
        }