public void Serialize(object val, BMSByte buffer) { var strBytes = Encoding.UTF8.GetBytes(val == null ? string.Empty : (string)val); buffer.Append(BitConverter.GetBytes(strBytes.Length)); buffer.Append(strBytes); }
public void Serialize(object val, BMSByte buffer) { var vec = (Vector3D)val; buffer.Append(BitConverter.GetBytes(vec.X)); buffer.Append(BitConverter.GetBytes(vec.Y)); buffer.Append(BitConverter.GetBytes(vec.Z)); }
public void Serialize(object val, BMSByte buffer) { var quat = (Quaternion)val; buffer.Append(BitConverter.GetBytes(quat.x)); buffer.Append(BitConverter.GetBytes(quat.y)); buffer.Append(BitConverter.GetBytes(quat.z)); buffer.Append(BitConverter.GetBytes(quat.w)); }
public void Serialize(object val, BMSByte buffer) { var listing = (ServerListingEntry[])val; buffer.Append(BitConverter.GetBytes(listing.Length)); foreach (var l in listing) { byte[] strBuf = Encoding.UTF8.GetBytes(l.Address ?? string.Empty); buffer.Append(BitConverter.GetBytes(strBuf.Length)); buffer.Append(strBuf); buffer.Append(BitConverter.GetBytes(l.Port)); } }
public void SendAndReceiveBuffer_ShouldBeEqual() { BMSByte msg = new BMSByte(); msg.Append(new byte[] { 3, 6, 9 }); BMSByte buffer = new BMSByte(); buffer.SetArraySize(512); ForgeTCPSocket server = new ForgeTCPSocket(); server.Listen(TEST_PORT, 100); Task backgroundThread = Task.Run(() => { var connectedClient = server.AwaitAccept(); connectedClient.Send(A.Fake <EndPoint>(), msg); }); EndPoint ep = new IPEndPoint(IPAddress.Parse(CommonSocketBase.LOCAL_IPV4), 15937); ForgeTCPSocket client = new ForgeTCPSocket(); client.Connect(LOCAL_IP, TEST_PORT); int readLength = client.Receive(buffer, ref ep); client.Close(); server.Close(); Assert.AreEqual(msg.Size, readLength); Assert.AreEqual(msg.Size, buffer.Size); for (int i = 0; i < msg.Size; ++i) { Assert.AreEqual(msg[i], buffer[i]); } }
protected override BMSByte SerializeDirtyFields() { if (dirtyFields.Length == 0 || !hasDirtyFields) { return(null); } // TODO: Check if is owner when calling this method BMSByte data = new BMSByte(); data.Append(dirtyFields); // Check to see if the field is dirty if ((0x1 & dirtyFields[0]) != 0) { ObjectMapper.Instance.MapBytes(data, num); } // Reset all of the dirty fields flags for (int i = 0; i < dirtyFields.Length; i++) { dirtyFields[i] = 0; } hasDirtyFields = false; return(data); }
public void StartClient(string address, ushort port, INetworkMediator netMediator) { networkMediator = netMediator; _socket.Connect(address, port); CancellationSource = new CancellationTokenSource(); Task.Run(ReadNetwork, CancellationSource.Token); BMSByte buffer = new BMSByte(); buffer.Append(new byte[] { 1 }); _socket.Send(_socket.EndPoint, buffer); }
/// <summary> /// Callback for user auth. Authenticates the user and sends the user their network id for acceptance. /// </summary> private void AuthUser(NetworkingPlayer player) { OnPlayerAuthenticated(player); // If authenticated, send the player their network id and accept them var buffer = new BMSByte(); buffer.Append(BitConverter.GetBytes(player.NetworkId)); Send(player, new Binary(Time.Timestep, false, buffer, Receivers.Target, MessageGroupIds.NETWORK_ID_REQUEST, false), true); SendBuffer(player); }
public void AppendBytesRemoveStart3() { byte[] data = new byte[] { 1, 8, 9, 34, 255, 0, 33, 66, 100, 128 }; var cache = new BMSByte(); cache.Append(data); cache.RemoveStart(3); for (int i = 3; i < data.Length; i++) { Assert.AreEqual(data[i], cache[i - 3]); } }
public void AppendBytesAndCompressBytes() { byte[] data = new byte[] { 1, 8, 9, 34, 255, 0, 33, 66, 100, 128 }; var cache = new BMSByte(); cache.Append(data); Assert.AreEqual(data.Length, cache.Size); for (int i = 0; i < data.Length; i++) { Assert.AreEqual(data[i], cache[i]); } }
public void AppendBytesRemoveStart3Add3ToEnd() { int removeSize = 3; byte[] data = new byte[] { 1, 8, 9, 34, 255, 0, 33, 66, 100, 128 }; var cache = new BMSByte(); cache.Append(data); cache.RemoveStart(removeSize); byte[] trailer = new byte[] { 9, 3, 9 }; cache.Append(trailer); for (int i = removeSize; i < data.Length; i++) { Assert.AreEqual(data[i], cache[i - removeSize]); Assert.AreEqual(data[i], cache[i - removeSize]); } for (int i = trailer.Length - 1; i >= 0; i--) { Assert.AreEqual(trailer[i], cache[cache.Size - trailer.Length + i]); } }
public void Serialize(object val, BMSByte buffer) { byte[] obj = (byte[])val; using (var stream = new MemoryStream()) { using (var writer = new BinaryWriter(stream)) { writer.Write(BitConverter.GetBytes(obj.Length)); writer.Write(obj); } buffer.Append(stream.ToArray()); } }
public void AcceptChallenge(NetWorker networker, BMSByte challenge, Action <BMSByte> authServerAction, Action rejectServerAction) { Server.AuthStatus status = challenge.GetBasicType <Server.AuthStatus>(); switch (status) { case Server.AuthStatus.Available: List <uint> memberIds = new List <uint>(); /*foreach (Friend f in ourLobby.Members) * { * memberIds.Add(f.Id.AccountId); * }*/ BMSByte response = ObjectMapper.BMSByte(SteamClient.SteamId.AccountId); BinaryFormatter binFor = new BinaryFormatter(); MemoryStream memStream = new MemoryStream(); binFor.Serialize(memStream, memberIds); //response.Append(ObjectMapper.BMSByte(memberIds.ToArray())); response.Append(ObjectMapper.BMSByte(memStream.ToArray())); authServerAction(response); memStream.Close(); return; case Server.AuthStatus.Checking: authServerAction(ObjectMapper.BMSByte(SteamClient.SteamId.AccountId)); return; case Server.AuthStatus.Closed: rejectServerAction(); return; } /* * BMSByte by = new BMSByte(); * var binFormatter = new BinaryFormatter(); * var mStream = new MemoryStream(); * binFormatter.Serialize(mStream, allowedSteamIDs); * * var data = ObjectMapper.BMSByte(mStream.ToArray()); * * authServerAction(data); */ }
/// <summary> /// Get a byte[] out of a BMSByte /// </summary> /// <param name="args">Arguments passed through to get mapped</param> /// <returns>A byte[] of the mapped arguments</returns> /// <summary> ///从BMSByte中获取一个字节[] /// </ summary> /// <param name =“args”>传递给映射的参数</ param> /// <returns>映射参数的一个byte [] </ returns> public BMSByte MapBytes(BMSByte bytes, params object[] args) { byte[][] bytesToMap = new byte[args.Length][]; for (int i = 0; i < args.Length; i++) { Type type = null; if (args[i] != null) { type = args[i].GetType(); } bytesToMap[i] = GetBytesArray(args[i], type); } bytes.Append(bytesToMap); return(bytes); }
public void CloneAndCompareBytes() { int removeSize = 3; byte[] data = new byte[] { 1, 8, 9, 34, 255, 0, 33, 66, 100, 128 }; var cache = new BMSByte(); cache.Append(data); cache.RemoveStart(removeSize); var copy = new BMSByte(); copy.Clone(cache); for (int i = 0; i < data.Length - removeSize; i++) { Assert.AreEqual(copy[i], cache[i]); } }
public void ConnectingPlayer_ShouldBePresentedAChallenge() { var netContainer = A.Fake <INetworkMediator>(); var serverFacade = AbstractFactory.Get <INetworkTypeFactory>().GetNew <ISocketServerFacade>(); serverFacade.StartServer(15937, 10, netContainer); var client = AbstractFactory.Get <INetworkTypeFactory>().GetNew <IClientSocket>(); client.Connect(CommonSocketBase.LOCAL_IPV4, 15937); BMSByte buffer = new BMSByte(); buffer.Append(new byte[] { 1 }); client.Send(client.EndPoint, buffer); Thread.Sleep(50); A.CallTo(() => netContainer.MessageBus.SendReliableMessage(A <IChallengeMessage> ._, A <ISocket> ._, A <EndPoint> ._)).MustHaveHappenedOnceExactly(); client.Close(); serverFacade.ShutDown(); }
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); } } }
public static void DynamicCommand(NetWorker socket, string command, bool relayOnServer = true, bool reliable = true) { BMSByte data = new BMSByte(); data.Append(new byte[] { 7 }); ObjectMapper.MapBytes(data, command); socket.WriteRaw(data, "BMS_INTERNAL_Command_" + command, relayOnServer, reliable); }
/// <summary> /// Gets the bytes for the Instance of an Object and appends them to a <c>BMSByte</c>. /// </summary> /// <param name="o">The Instance of the Object.</param> /// <param name="type">The Type of the Object.</param> /// <param name="bytes"><c>BMSByte</c> to which the bytes should be added.</param> protected virtual void GetBytes(object o, Type type, ref BMSByte bytes) { if (type == typeof(string)) { var strBytes = Encoding.UTF8.GetBytes(o == null ? string.Empty : (string)o); // TODO: Need to make custom string serialization to binary bytes.Append(BitConverter.GetBytes(strBytes.Length)); if (strBytes.Length > 0) { bytes.Append(strBytes); } } else if (type == typeof(Vector)) { Vector vec = (Vector)o; bytes.Append(BitConverter.GetBytes(vec.x)); bytes.Append(BitConverter.GetBytes(vec.y)); bytes.Append(BitConverter.GetBytes(vec.z)); } else if (type == null) //TODO: Check if this causes other issues { bytes.Append(new byte[1] { 0 }); } else if (type == typeof(sbyte)) { bytes.BlockCopy <sbyte>(o, 1); } else if (type == typeof(byte)) { bytes.BlockCopy <byte>(o, 1); } else if (type == typeof(char)) { bytes.BlockCopy <char>(o, 1); } else if (type == typeof(bool)) { bytes.Append(BitConverter.GetBytes((bool)o)); } else if (type == typeof(short)) { bytes.Append(BitConverter.GetBytes((short)o)); } else if (type == typeof(ushort)) { bytes.Append(BitConverter.GetBytes((ushort)o)); } else if (type == typeof(int)) { bytes.Append(BitConverter.GetBytes((int)o)); } else if (type == typeof(uint)) { bytes.Append(BitConverter.GetBytes((uint)o)); } else if (type == typeof(long)) { bytes.Append(BitConverter.GetBytes((long)o)); } else if (type == typeof(ulong)) { bytes.Append(BitConverter.GetBytes((ulong)o)); } else if (type == typeof(float)) { bytes.Append(BitConverter.GetBytes((float)o)); } else if (type == typeof(double)) { bytes.Append(BitConverter.GetBytes((double)o)); } else if (type.IsArray) { int rank = type.GetArrayRank(); Type targetType = type.GetElementType(); if (targetType != typeof(byte)) { throw new Exception("Currently only byte arrays can be sent as arrays"); } if (rank > 4) { throw new Exception("Currently the system only supports up to 4 dimensions in an array"); } int i, j, k, l; // Write each dimension length first int[] lengths = new int[rank]; for (i = 0; i < rank; i++) { lengths[i] = ((Array)o).GetLength(i); bytes.Append(BitConverter.GetBytes(lengths[i])); } switch (rank) { case 1: for (i = 0; i < lengths[0]; i++) { GetBytes(((Array)o).GetValue(i), targetType, ref bytes); } break; case 2: for (i = 0; i < lengths[0]; i++) { for (j = 0; j < lengths[1]; j++) { GetBytes(((Array)o).GetValue(i, j), targetType, ref bytes); } } break; case 3: for (i = 0; i < lengths[0]; i++) { for (j = 0; j < lengths[1]; j++) { for (k = 0; k < lengths[2]; k++) { GetBytes(((Array)o).GetValue(i, j, k), targetType, ref bytes); } } } break; case 4: for (i = 0; i < lengths[0]; i++) { for (j = 0; j < lengths[1]; j++) { for (k = 0; k < lengths[2]; k++) { for (l = 0; l < lengths[3]; l++) { GetBytes(((Array)o).GetValue(i, j, k, l), targetType, ref bytes); } } } } break; } } else if (type == typeof(BMSByte)) { bytes.Append(BitConverter.GetBytes(((BMSByte)o).Size)); bytes.BlockCopy(((BMSByte)o).byteArr, ((BMSByte)o).StartIndex(), ((BMSByte)o).Size); } else if (type.IsEnum) { GetBytes(o, Enum.GetUnderlyingType(type), ref bytes); } else { // TODO: Make this a more appropriate exception throw new BaseNetworkException("The type " + type.ToString() + " is not allowed to be sent over the Network (yet)"); } }
/// <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) } if (frame[0] == Binary.CONTROL_BYTE) { length += 1; } // Determine the length of the payload int dataStartIndex = 0; if (length <= 125) { frame[1] = (byte)length; dataStartIndex = 2; } else if (length >= 126 && length <= 65535) { dataStartIndex = 4; frame[1] = 126; } else { dataStartIndex = 10; frame[1] = 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)((payload.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 + payload.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.Append(new byte[] { (byte)Receivers }); } // 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]); } } }
/// <summary> /// Gets the bytes for the Instance of an Object and appends them to a <c>BMSByte</c>. /// </summary> /// <param name="o">The Instance of the Object.</param> /// <param name="type">The Type of the Object.</param> /// <param name="bytes"><c>BMSByte</c> to which the bytes should be added.</param> protected override void GetBytes(object o, Type type, ref BMSByte bytes) { if (type == typeof(Vector2)) { bytes.Append(BitConverter.GetBytes(((Vector2)o).x)); bytes.Append(BitConverter.GetBytes(((Vector2)o).y)); } else if (type == typeof(Vector3)) { bytes.Append(BitConverter.GetBytes(((Vector3)o).x)); bytes.Append(BitConverter.GetBytes(((Vector3)o).y)); bytes.Append(BitConverter.GetBytes(((Vector3)o).z)); } else if (type == typeof(Vector4)) { bytes.Append(BitConverter.GetBytes(((Vector4)o).x)); bytes.Append(BitConverter.GetBytes(((Vector4)o).y)); bytes.Append(BitConverter.GetBytes(((Vector4)o).z)); bytes.Append(BitConverter.GetBytes(((Vector4)o).w)); } else if (type == typeof(Color)) { bytes.Append(BitConverter.GetBytes(((Color)o).r)); bytes.Append(BitConverter.GetBytes(((Color)o).g)); bytes.Append(BitConverter.GetBytes(((Color)o).b)); bytes.Append(BitConverter.GetBytes(((Color)o).a)); } else if (type == typeof(Quaternion)) { bytes.Append(BitConverter.GetBytes(((Quaternion)o).x)); bytes.Append(BitConverter.GetBytes(((Quaternion)o).y)); bytes.Append(BitConverter.GetBytes(((Quaternion)o).z)); bytes.Append(BitConverter.GetBytes(((Quaternion)o).w)); } else { base.GetBytes(o, type, ref bytes); } }
public void Serialize(object val, BMSByte buffer) { buffer.Append(BitConverter.GetBytes((ulong)val)); }
/// <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="port">The port of the <see cref="NetWorker"/> that is to send 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(ushort port, NetworkingPlayer targetPlayer, string sceneName) { if (!Sockets.ContainsKey(port)) throw new NetworkException("There isn't a server running using the specified port on this machine"); if (!Sockets[port].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"); BMSByte data = new BMSByte(); data.Append(new byte[] { 2 }); ObjectMapper.MapBytes(data, sceneName); Sockets[port].WriteRaw(targetPlayer, data, "BMS_INTERNAL_Change_Client_Scene", true); }
/// <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.Append(new byte[] { 2 }); ObjectMapper.MapBytes(data, sceneName); netWorker.WriteRaw(targetPlayer, data, "BMS_INTERNAL_Change_Client_Scene", true); }
/// <summary> /// This will set the message group for the specified socket connection /// </summary> /// <param name="socket">The NetWorker to assign the message group for</param> /// <param name="groupId">The unique identifier for the message group</param> public static void SetMyMessageGroup(NetWorker socket, ushort groupId) { socket.Me.SetMessageGroup(groupId); BMSByte data = new BMSByte(); data.Append(new byte[] { 6 }); ObjectMapper.MapBytes(data, groupId); socket.WriteRaw(data, "BMS_INTERNAL_Set_MessageGroup", true, true); }
/// <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="port">The port of the <see cref="NetWorker"/> that is to send the message</param> /// <param name="sceneName">The name of the scene in which the client should load</param> public static void ChangeClientScene(ushort port, string sceneName) { if (!Sockets.ContainsKey(port)) throw new NetworkException("There isn't a server running using the specified port on this machine"); if (!Sockets[port].IsServer) throw new NetworkException("Only the server can call this method, the NetWorker on the specified port is not a server"); BMSByte data = new BMSByte(); data.Append(new byte[] { 2 }); ObjectMapper.MapBytes(data, sceneName); Sockets[port].WriteRaw(data, "BMS_INTERNAL_Change_Client_Scene", false, true); }
public void Serialize(object val, BMSByte buffer) { buffer.Append(new byte[1] { (byte)((sbyte)val) }); }