internal void Initialize(NetEventType type, NetPeer peer) { Reset(); length = 0; EventType = type; Peer = peer; }
private static NetEvent CreateEvent(NetEventType type, NetPeer peer) { NetEvent evnt = new NetEvent(); evnt.Initialize(type, peer); return(evnt); }
public override NetEventType PollEvent(out ulong clientId, out string channelName, out ArraySegment <byte> payload, out float receiveTime) { if (_lastProcessedTransportIndex >= Transports.Length - 1) { _lastProcessedTransportIndex = 0; } for (byte i = _lastProcessedTransportIndex; i < Transports.Length; i++) { _lastProcessedTransportIndex = i; if (Transports[i].IsSupported) { NetEventType @eventType = Transports[i].PollEvent(out ulong connectionId, out channelName, out payload, out receiveTime); if (@eventType != NetEventType.Nothing) { clientId = GetMLAPIClientId(i, connectionId, false); return(@eventType); } } } clientId = 0; channelName = null; payload = new ArraySegment <byte>(); receiveTime = 0; return(NetEventType.Nothing); }
internal void Initialize( NetEventType type, NetPeer peer) { this.Reset(); this.length = 0; this.EventType = type; this.Peer = peer; }
public static void Trigger(NetEventType eventName, NetEventArgs args) { NetworkEvent e = null; if (instance.events.TryGetValue(eventName, out e)) { e.Invoke(args); } }
public void NotifyEvent(NetEventType m_event, params object[] param) { for (int i = 0; i < mgrEventList.Count; i++) { if (mgrEventList[i].eventType == m_event) { mgrEventList[i].handle(param); } } }
void Update() { if (mEvents.Count > 0) { while (mEvents.Count > 0) { NetEventType _event = mEvents.Dequeue(); _event.Key(_event.Value); } } }
public void Register(NetEventType m_eventType, EventManager.VoidHandle handle) { if (m_eventList.ContainsKey(m_eventType) == false) { m_eventList.Add(m_eventType, handle); } else { } //SimpleFramework.Util.LogError("{0}已经被注册了", m_eventType.ToString()); }
public void RegistEvent(NetEventType m_event, VoidHandle handle) { MgrEvent tmp = new MgrEvent(); tmp.eventType = m_event; tmp.handle = handle; if (mgrEventList.Contains(tmp) == false) { mgrEventList.Add(tmp); } }
public void Connected(NetEventType type) { if (NetEventType.Connected == type) { Debug.Log("Login Success!"); } else if (NetEventType.ConnectionRefused == type) { Debug.LogError("Login Fail!"); } }
public void RemoveEvent(NetEventType m_event, VoidHandle handle) { for (int i = 0; i < mgrEventList.Count; i++) { if (mgrEventList[i].eventType == m_event) { mgrEventList.RemoveAt(i); i--; } } }
private NetEvent CreateEvent( NetEventType type, NetPeer target) { NetEvent evnt = eventPool.Allocate(); evnt.Initialize( type, target); return(evnt); }
public void Log(NetEventType type) { if (!this.logging) { return; } if (!this.recvList.ContainsKey(type)) { this.recvList[type] = new List <float>(); } this.recvList[type].Add(Time.realtimeSinceStartup); }
public static void AddListener(NetEventType type, UnityAction <NetEventArgs> listener) { NetworkEvent e = null; if (instance.events.TryGetValue(type, out e)) { e.AddListener(listener); } else { e = new NetworkEvent(); e.AddListener(listener); instance.events.Add(type, e); } }
private NetEvent CreateEvent(NetEventType type) { NetEvent evt = null; if (_netEventsPool.Count > 0) { evt = _netEventsPool.Pop(); } if (evt == null) { evt = new NetEvent(); } evt.Type = type; return(evt); }
/// <summary> /// Retrieves an event from the js library, handles it internally and then adds it to a queue for delivery to the user. /// </summary> /// <param name="evt"> The new network event or an empty struct if none is found.</param> /// <returns>True if event found, false if no events queued.</returns> private bool DequeueInternal(out NetworkEvent evt) { int length = UnityWebRtcNetworkPeekEventDataLength(mReference); if (length == -1) //-1 == no event available { evt = new NetworkEvent(); return(false); } else { ByteArrayBuffer buf = ByteArrayBuffer.Get(length); bool eventFound = UnityWebRtcNetworkDequeue(mReference, mTypeidBuffer, mConidBuffer, buf.array, 0, buf.array.Length, mDataWrittenLenBuffer); //set the write correctly buf.PositionWriteRelative = mDataWrittenLenBuffer[0]; NetEventType type = (NetEventType)mTypeidBuffer[0]; ConnectionId id; id.id = (short)mConidBuffer[0]; object data = null; if (buf.PositionWriteRelative == 0 || buf.PositionWriteRelative == -1) //no data { data = null; //was an empty buffer -> release it and buf.Dispose(); } else if (type == NetEventType.ReliableMessageReceived || type == NetEventType.UnreliableMessageReceived) { //store the data for the user to use data = buf; } else { //non data message with data attached -> can only be a string string stringData = Encoding.ASCII.GetString(buf.array, 0, buf.PositionWriteRelative); data = stringData; buf.Dispose(); } evt = new NetworkEvent(type, id, data); UnityEngine.Debug.Log("event" + type + " received"); HandleEventInternally(ref evt); return(eventFound); } }
/// <summary> /// Retrieves an event from the js library, handles it internally and then adds it to a queue for delivery to the user. /// </summary> /// <param name="evt"> The new network event or an empty struct if none is found.</param> /// <returns>True if event found, false if no events queued.</returns> private bool DequeueInternal(out NetworkEvent evt) { int length = CAPI.Unity_WebRtcNetwork_PeekEventDataLength(mReference); if (length == -1) //-1 == no event available { evt = new NetworkEvent(); return(false); } else { ByteArrayBuffer buf = ByteArrayBuffer.Get(length); bool eventFound = CAPI.Unity_WebRtcNetwork_Dequeue(mReference, mTypeidBuffer, mConidBuffer, buf.array, 0, buf.array.Length, mDataWrittenLenBuffer); //set the write correctly buf.PositionWriteRelative = mDataWrittenLenBuffer[0]; NetEventType type = (NetEventType)mTypeidBuffer[0]; ConnectionId id; id.id = (short)mConidBuffer[0]; //TODO: add a way to move error information from java script to Unity for //NetworkEvent.ErrorInfo if (buf.PositionWriteRelative == 0 || buf.PositionWriteRelative == -1) //no data { //was an empty buffer -> release it and buf.Dispose(); evt = new NetworkEvent(type, id); } else if (type == NetEventType.ReliableMessageReceived || type == NetEventType.UnreliableMessageReceived) { evt = new NetworkEvent(type, id, buf); } else { //non data message with data attached -> can only be a string string stringData = Encoding.ASCII.GetString(buf.array, 0, buf.PositionWriteRelative); evt = new NetworkEvent(type, id, stringData); buf.Dispose(); } UnityEngine.Debug.Log("event" + type + " received"); HandleEventInternally(ref evt); return(eventFound); } }
public static void RemoveListener(NetEventType type, UnityAction <NetEventArgs> listener) { if (!instance) { return; } NetworkEvent e = null; if (instance.events.TryGetValue(type, out e)) { e.RemoveListener(listener); if (e.GetPersistentEventCount() == 0) { instance.events.Remove(type); } } }
protected NetEvent CreateEvent(NetEventType type) { NetEvent evt; if (_netEventsPool.Count > 0) { lock (_netEventsPool) { evt = _netEventsPool.Pop(); } } else { evt = new NetEvent(); evt.DataReader = new NetDataReader(); } evt.Type = type; return(evt); }
private NetEvent CreateEvent(NetEventType type) { NetEvent evt = null; lock (_netEventsPool) { if (_netEventsPool.Count > 0) { evt = _netEventsPool.Pop(); } } if (evt == null) { evt = new NetEvent { DataReader = new NetDataReader() }; } evt.Type = type; return(evt); }
void Update() { for (int i = 0; i < 3 && eventQueue.Count > 0; i++) { NetEventType e = (NetEventType)eventQueue[0]; eventQueue.RemoveAt(0); if (onNetEvent != null) { onNetEvent(e); } } for (int i = 0; i < 3 && packetQueue.Count > 0; i++) { Packet p = (Packet)packetQueue[0]; packetQueue.RemoveAt(0); if (onReceivePacketEvent != null) { onReceivePacketEvent(p); } } }
private NetEvent CreateEvent(NetEventType type) { NetEvent evt = null; if (type == NetEventType.Connect) { _connectedPeersCount++; } lock (_netEventsPool) { if (_netEventsPool.Count > 0) { evt = _netEventsPool.Pop(); } } if (evt == null) { evt = new NetEvent(); } evt.Type = type; return(evt); }
private static NetEvent CreateEvent(NetEventType type, NetPeer peer) { NetEvent evnt = new NetEvent(); evnt.Initialize(type, peer); return evnt; }
internal NetworkEvent(NetEventType t) { type = t; connectionId = ConnectionId.INVALID; data = null; }
internal NetworkEvent(NetEventType t, ConnectionId conId, object dt) { type = t; connectionId = conId; data = dt; }
protected NetEvent CreateEvent(NetEventType type) { NetEvent evt = null; lock (_netEventsPool) { if (_netEventsPool.Count > 0) { evt = _netEventsPool.Pop(); } } if(evt == null) { evt = new NetEvent {DataReader = new NetDataReader()}; } evt.Type = type; return evt; }
/// <summary> /// Creates a new network event of a certain type setting /// connection id to invalid and data to null. /// /// Internal only. Do not use. /// </summary> /// <param name="t">The type of this event</param> internal NetworkEvent(NetEventType t) { type = t; connectionId = ConnectionId.INVALID; data = null; }
private void HandleRawTransportPoll(NetEventType eventType, ulong sendingClientID, byte channel, ArraySegment <byte> payload, float receiveTime) { switch (eventType) { case NetEventType.Connect: if (isServer) { m_PendingClients.Add(new PendingClient() { clientID = sendingClientID, connectionState = PendingClient.State.PendingConnection }); m_PendingClientsDictionary.Add(sendingClientID, m_PendingClients[m_PendingClients.Count - 1]); StartCoroutine(ApprovalTimeout(sendingClientID)); } else { if (enableLogging) { Debug.Log("Connected"); } SendConnectionRequest(); StartCoroutine(ApprovalTimeout(sendingClientID)); } break; case NetEventType.Data: if (enableLogging) { Debug.Log($"Incoming Data From {sendingClientID} : {payload.Count} bytes"); } HandleIncomingData(sendingClientID, channel, payload, receiveTime); break; case NetEventType.Disconnect: if (enableLogging) { Debug.Log("Client disconnect: " + sendingClientID); } if (isServer) { OnClientDisconnectFromServer(sendingClientID); } else { isConnected = false; StopClient(); } for (int i = 0; i < m_Modules.Count; i++) { m_Modules[i].OnClientDisconnect(sendingClientID); } onClientDisconnect?.Invoke(sendingClientID); break; } }
/// <summary> /// Creates a network event with the given content /// /// Internal only. Do not use. /// </summary> /// <param name="t">Typename</param> /// <param name="conId">ConnectionId the event is from / relates to</param> /// <param name="dt">Data. String or MessageDataBuffer</param> internal NetworkEvent(NetEventType t, ConnectionId conId, object dt) { type = t; connectionId = conId; data = dt; }
private void fireNetEvent(NetEventType type, Object data) { if(eventDriven) { foreach(NetEventListener listener in listeners) { listener(type, data); } } else { lock(locker) { networkEvents.Enqueue(new Tuple<NetEventType, Object>(type, data)); } } }
private static void RunLoop() { NetEventType eventType = Transport.Poll(out ulong connectionId, out byte channelId, out ArraySegment <byte> payload); switch (@eventType) { case NetEventType.Data: { // Last byte is the messageType MessageType messageType = (MessageType)payload.Array[payload.Offset + payload.Count - 1]; switch (messageType) { case MessageType.StartServer: { // Check if they are already connected or perhaps are already hosting, if so return if (HasPeer(connectionId)) { return; } Client client; // Create the room Room room = new Room(client = new Client() { ConnectionId = connectionId, IsServer = true, OutgoingBytes = 0, ConnectTime = DateTime.UtcNow }); // Add the room Rooms.Add(room); // Resolve the endpoint IPEndPoint endpoint = Transport.GetEndPoint(connectionId); if (endpoint != null) { // Make address IPv6 endpoint = new IPEndPoint(endpoint.Address.MapToIPv6(), endpoint.Port); if (Config.EnableRuntimeMetaLogging) { Console.WriteLine("[INFO] Server started from " + endpoint); } ServerAddressToRoom.Add(endpoint, room); } } break; case MessageType.ConnectToServer: { // Check if they are already connected or perhaps are already hosting, if so return if (HasPeer(connectionId)) { return; } if (payload.Count < 1 + 2 + 16) { // Invalid size return; } // 1 for messageType, 2 for port, 16 for address int addressOffset = payload.Count - (1 + 2 + 16); // 1 for messageType, 2 for port int portOffset = payload.Count - (1 + 2); // Copy the address for (int i = 0; i < 16; i++) { ADDRESS_BYTE_ARRAY[i] = payload.Array[payload.Offset + addressOffset + i]; } // Read port ushort port = (ushort)(((ushort)payload.Array[payload.Offset + portOffset]) | ((ushort)payload.Array[payload.Offset + portOffset + 1] << 8)); // Parse address IPAddress address = new IPAddress(ADDRESS_BYTE_ARRAY); // Create endpoint IPEndPoint endpoint = new IPEndPoint(address, port); if (Config.EnableRuntimeMetaLogging) { Console.WriteLine("[INFO] Connection requested to address " + endpoint); } if (ServerAddressToRoom.ContainsKey(endpoint)) { if (Config.EnableRuntimeMetaLogging) { Console.WriteLine("[INFO] Connection approved"); } // Get the room they want to join Room room = ServerAddressToRoom[endpoint]; // Create a client for them Client client = new Client() { ConnectionId = connectionId, IsServer = false, ConnectTime = DateTime.UtcNow, OutgoingBytes = 0 }; // Handle the connect room.HandleClientConnect(client); } } break; case MessageType.Data: { foreach (Room room in Rooms) { if (room.HasPeer(connectionId, out bool isServer)) { // Found a matching client in room if (isServer) { // The server is sending data ulong destination = (((ulong)payload.Array[payload.Offset + payload.Count - 9]) | ((ulong)payload.Array[payload.Offset + payload.Count - 8] << 8) | ((ulong)payload.Array[payload.Offset + payload.Count - 7] << 16) | ((ulong)payload.Array[payload.Offset + payload.Count - 6] << 24) | ((ulong)payload.Array[payload.Offset + payload.Count - 5] << 32) | ((ulong)payload.Array[payload.Offset + payload.Count - 4] << 40) | ((ulong)payload.Array[payload.Offset + payload.Count - 3] << 48) | ((ulong)payload.Array[payload.Offset + payload.Count - 2] << 56)); // Safety check. Make sure who they want to send to ACTUALLY belongs to their room if (room.HasPeer(destination, out isServer) && !isServer) { // We strip the connectionId. Since this is from the server, a source is not needed. payload.Array[payload.Offset + payload.Count - 9] = (byte)MessageType.Data; // [data, data, data, dest1, dest2, dest3, dest4, dest5, dest6, dest7, dest8, mtype_r, none, none, none] => [{data, data, data, mtype_s}, dest2, dest3, dest4, dest5, dest6, dest7, dest8, mtype_r, none, none, none] // Send a shrunk version of the array. room.Send(destination, connectionId, channelId, new ArraySegment <byte>(payload.Array, payload.Offset, payload.Count - 8)); } } else { // A client is sending data int writeOffset = 0; byte[] buffer = null; if (payload.Array.Length < payload.Count + sizeof(ulong)) { if (Program.MESSAGE_BUFFER.Length < payload.Count + sizeof(ulong)) { // Message buffer cannot fit the payload either. // Check if we can alloc temporary memory if (Config.AllowTemporaryAlloc && Config.MaxTemporaryAlloc >= payload.Count + sizeof(ulong)) { // We are allowed to alloc this amount! // Alloc a large enough buffer writeOffset = 0; buffer = new byte[payload.Count + sizeof(ulong)]; } } else { // Message buffer can store it! writeOffset = 0; buffer = Program.MESSAGE_BUFFER; } if (buffer != null) { // We have something alloced. Lets copy the current payload! Buffer.BlockCopy(payload.Array, payload.Offset, buffer, writeOffset, payload.Count); } } else { buffer = payload.Array; writeOffset = payload.Offset; } if (buffer != null) { // Write the connectionId at the end of the recieved message (because optimization) // We use -1 because we actually want to overwrite the last byte in the message, since that is the old messageType location. It will be moved forward now. for (byte i = 0; i < sizeof(ulong); i++) { buffer[writeOffset + payload.Count - 1 + i] = ((byte)(connectionId >> (i * 8))); } // Write the message type at the new end buffer[writeOffset + payload.Count + 7] = (byte)MessageType.Data; // Send the expanded array room.Send(room.ServerConnectionId, connectionId, channelId, new ArraySegment <byte>(payload.Array, payload.Offset, payload.Count + sizeof(ulong))); } else { // Message is too large. Drop it } } // Exit loop when room is found break; } } } break; case MessageType.ClientDisconnect: { ulong clientConnectionId = (((ulong)payload.Array[payload.Offset]) | ((ulong)payload.Array[payload.Offset + 1] << 8) | ((ulong)payload.Array[payload.Offset + 2] << 16) | ((ulong)payload.Array[payload.Offset + 3] << 24) | ((ulong)payload.Array[payload.Offset + 4] << 32) | ((ulong)payload.Array[payload.Offset + 5] << 40) | ((ulong)payload.Array[payload.Offset + 6] << 48) | ((ulong)payload.Array[payload.Offset + 7] << 56)); if (Config.EnableRuntimeMetaLogging) { Console.WriteLine("[INFO] Client disconnect request"); } foreach (Room room in Rooms) { if (room.ServerConnectionId == connectionId && room.HandleClientDisconnect(clientConnectionId, true)) { // Only disconnect one. A peer can only be in 1 room break; } } } break; } } break; case NetEventType.Disconnect: { if (Config.EnableRuntimeMetaLogging) { Console.WriteLine("[INFO] Peer disconnected"); } foreach (Room room in Rooms) { if (room.HandleClientDisconnect(connectionId)) { // Each connection can only have 1 room break; } } } break; } }