Ejemplo n.º 1
0
 public void Send(BufferPool.Buffer datagram)
 {
     foreach (IPEndPoint broadcast in broadcastAddresses)
     {
         Send(broadcast, datagram);
     }
 }
Ejemplo n.º 2
0
            public ReceiveState(IPEndPoint ip)
            {
                this.ip = ip;

                data   = null;
                offset = 0;
            }
Ejemplo n.º 3
0
 public void Send(IPEndPoint endpoint, BufferPool.Buffer datagram)
 {
     if (datagram.Size > 0 && datagram.Size <= datagram.Data.Length)
     {
         udp.SendAsync(datagram.Data, (int)datagram.Size, endpoint);
     }
 }
Ejemplo n.º 4
0
        public void Send(Guid remote, ushort channel, BufferPool.Buffer data, bool dispose_buffer = true)
        {
            if (state == State.RUNNING)
            {
                Connection.Base[] client_channels;
                Connection.Base   client_channel;

                lock (openedChannels)
                {
                    if (!openedChannels.TryGetValue(remote, out client_channels))
                    {
                        throw new ArgumentException(string.Format("No connection with remote '{0}'. Nothing sent.", remote), "remote");
                    }

                    if (channel >= client_channels.Length || client_channels[channel] == null)
                    {
                        throw new ArgumentException(string.Format("Invalid channel. No channel with index '{0}'", channel), "channel");
                    }

                    client_channel = client_channels[channel];
                }

                client_channel.SendAsync(data, dispose_buffer);
            }
            else
            {
                Debug.LogWarningFormat("Can not send data when in state {0}. Nothing sent.", state);
            }
        }
Ejemplo n.º 5
0
        protected override void SendAsync(Threads.Result result, BufferPool.Buffer data, bool dispose_buffer = true)
        {
            try
            {
                if (Connected())
                {
                    Converter32 c = new Converter32(data.Size);

                    writeBuffer.Data[0] = c.Byte1;
                    writeBuffer.Data[1] = c.Byte2;
                    writeBuffer.Data[2] = c.Byte3;
                    writeBuffer.Data[3] = c.Byte4;

                    BeginSend(writeBuffer.Data, writeBuffer.Data.Length, FinalizeSendLength, new SendState(result, data, dispose_buffer));
                }
                else
                {
                    throw new ArgumentNullException("client", "The connection is not opened.");
                }
            }
            catch (Exception e)
            {
                result.Complete(e);
            }
        }
Ejemplo n.º 6
0
        public Socket(Negotiation.Base parent, Message.Negotiation.Parameters parameters, UnityAction <Base> disconnection_handler, System.Net.Sockets.Socket socket) : base(parent, parameters, disconnection_handler)
        {
            this.socket = socket;

            readBuffer  = new BufferPool.Buffer(null, new byte[sizeof(int)], false);
            writeBuffer = new BufferPool.Buffer(null, new byte[sizeof(int)], false);
        }
Ejemplo n.º 7
0
        protected void Worker()
        {
            WaitHandle[] wait = new WaitHandle[] { stopEvent, addEvent };

            BufferPool.Buffer heartbeat_data = new BufferPool.Buffer(null, new byte[0], false);

            int event_idx;

            while ((event_idx = WaitHandle.WaitAny(wait, parameters.heartbeat)) != 0)
            {
                if (event_idx == WaitHandle.WaitTimeout)
                {
                    // Handle heartbeat
                    if (sendResult == null || sendResult.Done)
                    {
                        sendResult = CreateResult();

                        SendAsync(sendResult, heartbeat_data, false);
                    }
                }
                else
                {
                    Threads.Task task = null;

                    lock (addEvent)
                    {
                        if (sendResult == null || sendResult.Done)
                        {
                            sendResult = null;

                            lock (sendQueue)
                            {
                                if (sendQueue.Count > 0)
                                {
                                    task = sendQueue.Dequeue();
                                }
                                else
                                {
                                    // Nothing to do anymore, go to sleep
                                    addEvent.Reset();
                                }
                            }
                        }
                        else
                        {
                            // Not done yet, go to sleep
                            addEvent.Reset();
                        }
                    }

                    if (task != null)
                    {
                        sendResult = (Threads.Result)task.result;

                        task.callback();
                    }
                }
            }
        }
Ejemplo n.º 8
0
        public Tcp(Negotiation.Base parent, Message.Negotiation.Parameters parameters, UnityAction <Base> disconnection_handler, TcpClient client) : base(parent, parameters, disconnection_handler, client.Client)
        {
            this.client = client;

            stream = null;

            headerBuffer = new BufferPool.Buffer(null, new byte[headerSize], false);
        }
Ejemplo n.º 9
0
            public void Set(BufferPool.Buffer data, uint size)
            {
                this.data = data;

                this.data.Size = size;

                offset = 0;
            }
Ejemplo n.º 10
0
        public void Receive(IPAddress remote, Guid id, ushort channel, BufferPool.Buffer data)
        {
            if (onReceive.GetPersistentEventCount() > 0)
            {
                lock (deserializationTasks)
                {
                    DeserializationContext context = new DeserializationContext(r => onReceive.Invoke(remote, id, channel, r));

                    context.task = serializer.Deserialize(new Binary.Buffer(data, serializer), context.DeserializationCallback, null);

                    deserializationTasks.Enqueue(context);
                }
            }
        }
Ejemplo n.º 11
0
        protected void FinalizeReceiveData(IAsyncResult async_result)
        {
            FinalizeReceive(async_result, state =>
            {
                BufferPool.Buffer data = state.data;                 // Otherwise the call to state.data in unity thread will be evaluated to null, because of the weird catching of parameters of lambdas

                Threads.APC.MonoBehaviourCall.Instance.Call(() => events.onReceive.Invoke(state.ip.Address, parameters.guid, parameters.channel, data));

                state.Set(readBuffer, (uint)readBuffer.Data.Length);

                // Wait for next message
                BeginReceive(state.data.Data, state.offset, state.MissingDataLength, FinalizeReceiveLength, state);
            });
        }
Ejemplo n.º 12
0
        public void SendAsync(BufferPool.Buffer data, bool dispose_buffer = true)
        {
            if (!disposed)
            {
                lock (sendQueue)
                {
                    Threads.Result result = CreateResult();

                    sendQueue.Enqueue(new Threads.Task(() => SendAsync(result, data, dispose_buffer), result));
                }

                lock (addEvent)
                {
                    addEvent.Set();
                }
            }
        }
Ejemplo n.º 13
0
        protected void SendBeacon(bool exist)
        {
            if (advertise != null)
            {
                foreach (Service service in advertise)
                {
                    if (service.server != null)
                    {
                        try
                        {
                            IServiceInfo info = service.info.ServiceInfo;

                            if (info != null)
                            {
                                info.Active = exist && service.server.CurrentState == Negotiation.Base.State.RUNNING;

                                BufferPool.Buffer data = serializer.Serialize(new Datagram(exist, service.server.port, info));

                                if (data != null && data.Size > 0)
                                {
                                    broadcast.Send(data);

                                    if (manualPeers != null)
                                    {
                                        foreach (Peer peer in manualPeers)
                                        {
                                            if (IPAddress.TryParse(peer.ip, out IPAddress ip))
                                            {
                                                broadcast.Send(new IPEndPoint(ip, peer.port), data);
                                            }
                                        }
                                    }
                                }
                            }
                        }
                        catch (Binary.SerializationException e) {
                            Debug.LogErrorFormat("{1}: {2}\n{3}", e.GetType(), e.Message, e.StackTrace);
                        }
                    }
                }
            }
        }
Ejemplo n.º 14
0
        protected bool ReceiveData(Stream stream, BufferPool.Buffer buffer, uint size)
        {
            int received = 0;

            try
            {
                while (received < size)
                {
                    received += stream.Read(buffer.Data, received, (int)(size - received));
                }
            }
            catch (Exception e)
            {
                HandleException(e);

                return(false);
            }

            return(true);
        }
Ejemplo n.º 15
0
        public void SendOthers(Guid remote, ushort channel, BufferPool.Buffer data, bool dispose_buffer = true)
        {
            if (state == State.RUNNING)
            {
                lock (openedChannels)
                {
                    if (dispose_buffer)
                    {
                        data.SetReferencesCount((uint)openedChannels.Count);
                    }

                    foreach (KeyValuePair <Guid, Connection.Base[]> pair in openedChannels)
                    {
                        if (remote == Guid.Empty || pair.Key != remote)
                        {
                            if (channel >= pair.Value.Length || pair.Value[channel] == null)
                            {
                                throw new ArgumentException(string.Format("Invalid channel. No channel with index '{0}'", channel), "channel");
                            }

                            pair.Value[channel].SendAsync(data, dispose_buffer);
                        }
                        else
                        {
                            if (dispose_buffer)
                            {
                                data.DecrementReferencesCount();
                            }
                        }
                    }
                }
            }
            else
            {
                Debug.LogWarningFormat("Can not send data when in state {0}. Nothing sent.", state);
            }
        }
Ejemplo n.º 16
0
 public void SendAll(ushort channel, BufferPool.Buffer data, bool dispose_buffer = true)
 {
     SendOthers(Guid.Empty, channel, data, dispose_buffer);
 }
Ejemplo n.º 17
0
 protected abstract void SendAsync(Threads.Result result, BufferPool.Buffer data, bool dispose_buffer = true);
Ejemplo n.º 18
0
 protected abstract void OnMonitorReceive(IPAddress address, Guid guid, ushort channel, BufferPool.Buffer data);
Ejemplo n.º 19
0
        protected override void OnMonitorReceive(IPAddress address, Guid guid, ushort channel, BufferPool.Buffer data)
        {
            Message.Base msg = ReceiveMonitorCommand(data);

            if (msg.IsType <Message.Negotiation.Channel.UDP>())
            {
                Message.Negotiation.Channel.UDP response = (Message.Negotiation.Channel.UDP)msg;

                ServerChannel channel_parameters = channels[response.channel];

                Message.Negotiation.Parameters param = new Message.Negotiation.Parameters
                {
                    guid          = response.guid,
                    channel       = response.channel,
                    type          = channel_parameters.type,
                    heartbeat     = channel_parameters.parameters.Heartbeat,
                    autoReconnect = !channel_parameters.parameters.disableAutoReconnect
                };

                Connection.Tcp monitor;

                if (monitors.TryGetValue(param.guid, out monitor))
                {
                    UdpConnectionParams udp_param = SendUdpParams(monitor, param);

                    ConnectUdp(udp_param, response);
                }
                else
                {
                    Debug.LogErrorFormat("No monitor channel with guid '{0}' to send UDP negotiation for channel {1}", param.guid, param.channel);
                }
            }
        }
Ejemplo n.º 20
0
 public SendState(Threads.Result result, BufferPool.Buffer data, bool dispose_buffer)
 {
     this.result         = result;
     this.data           = data;
     this.dispose_buffer = dispose_buffer;
 }
Ejemplo n.º 21
0
        protected override void OnMonitorReceive(IPAddress address, Guid guid, ushort channel, BufferPool.Buffer data)
        {
            Message.Base msg = ReceiveMonitorCommand(data);

            if (msg.IsType <Message.Negotiation.Channel.UDP>())
            {
                Message.Negotiation.Channel.UDP response = (Message.Negotiation.Channel.UDP)msg;

                UdpConnectionParams udp_params = null;

                lock (pendingUdpConnection)
                {
                    foreach (UdpConnectionParams pending_udp_params in pendingUdpConnection)
                    {
                        if (pending_udp_params.param.guid == response.guid && pending_udp_params.param.channel == response.channel)
                        {
                            udp_params = pending_udp_params;

                            break;
                        }
                    }

                    if (udp_params != null)
                    {
                        pendingUdpConnection.Remove(udp_params);
                    }
                }

                if (udp_params != null)
                {
                    ConnectUdp(udp_params, (Message.Negotiation.Channel.UDP)msg);
                }
                else
                {
                    Debug.LogError("Reiceved UDP connection parameters for unrequested connection.");
                }
            }
        }