public NetworkP2PMessage(NetBuffer buffer, NetConnection connection, NetChannel channel)
        {
            flags = 0;

            // read header from stream:

            var headerFlags = (HeaderFlags)buffer.ReadByte();

            internCode = (InternalCode)(headerFlags & HeaderFlags.InternalCode);
            isTypeSafe = ((headerFlags & HeaderFlags.IsTypeSafe) == HeaderFlags.IsTypeSafe);
            isReliable = ((int)channel & (int)NetChannel.ReliableUnordered) == (int)NetChannel.ReliableUnordered;

            if (!isInternal)
            {
                name = buffer.ReadString();
            }
            else
            {
                name = String.Empty;
            }

            stream          = new BitStream(buffer, isTypeSafe);
            this.connection = connection;
            this.channel    = channel;
        }
Example #2
0
        public void Connect(string name, NetChannel channel)
        {
            _clientName = name;
            _netChannel = channel;

            SignonState = ESignonState.Connected;
        }
Example #3
0
        /**
         * Creates a new CNSService
         *
         * @param cnsNode
         *            The NodeID of the Node with the CNS on it
         * @//throws JCSPNetworkException
         *             Thrown if something goes wrong in the underlying architecture
         */
        public CNSService(NodeID cnsNode)
        // //throws JCSPNetworkException
        {
            // Create the input and output channel
            this.toCNS   = NetChannel.one2net(new NetChannelLocation(cnsNode, 1), new CNSNetworkMessageFilter.FilterTX());
            this.fromCNS = NetChannel.net2one(new CNSNetworkMessageFilter.FilterRX());

            // We now need to logon to the CNS
            CNSMessage message = new CNSMessage();

            message.type      = CNSMessageProtocol.LOGON_MESSAGE;
            message.location1 = (NetChannelLocation)this.fromCNS.getLocation();
            this.toCNS.write(message);

            // Wait for logon reply message
            CNSMessage logonReply = (CNSMessage)this.fromCNS.read();

            // Check if we logged on OK
            if (logonReply.success == false)
            {
                Node.err.log(this.GetType(), "Failed to logon to CNS");
                throw new JCSPNetworkException("Failed to Logon to CNS");
            }
            Node.log.log(this.GetType(), "Logged into CNS");
        }
Example #4
0
        /// <summary>
        /// Sends the given message using the given UDP delivery type.  A client will send to the server, a server will broadcast.
        /// </summary>
        /// <param name="message">The message to be sent</param>
        /// <param name="deliveryType">The UDP delivery type</param>
        public void SendMessage(SpiderMessage message, NetChannel deliveryType)
        {
            NetMessage msg = new NetMessage();

            msg.Write(message.ToByteArray());
            spiderNet.SendMessage(msg, deliveryType);
        }
Example #5
0
 private void CreateMessageHandlers(NetChannel channel)
 {
     foreach (var type in handlerTypes)
     {
         MessageHandlerFactory.Create(type, channel);
     }
 }
        public void SendToAllExcept(Message msg, NetChannel channel, int excludedClientID)
        {
            if (!ActiveConnections.ContainsKey(excludedClientID))
                throw new System.InvalidOperationException("Excluded player not connected to network session");

            _serverMessageSender.SendToAllExcept(msg, channel, ActiveConnections[excludedClientID]);
        }
Example #7
0
        /**
         * Resolves a name on the CNS, retrieving the NetChannelLocation for the channel
         *
         * @param name
         *            The name to resolve
         * @return The NetChannelLocation of the channel declared name
         * @//throws JCSPNetworkException
         *             Thrown if something goes wrong in the underlying architecture
         */
        public NetChannelLocation resolve(String name)
        ////throws JCSPNetworkException
        {
            // Create a temporary channel to receive the incoming NetChannelLocation
            NetChannelInput In = NetChannel.net2one(new CNSNetworkMessageFilter.FilterRX());
            // Create a resolution message
            CNSMessage message = new CNSMessage();

            message.type      = CNSMessageProtocol.RESOLVE_REQUEST;
            message.location1 = (NetChannelLocation)In.getLocation();
            message.name      = name;
            // Write the resolution message to the CNS
            this.toCNS.write(message);
            // Read in reply
            CNSMessage reply = (CNSMessage)In.read();

            // Destroy the temporary channel
            In.destroy();
            // Now return the resolved location, or throw an exception
            if (reply.success == true)
            {
                return(reply.location1);
            }
            throw new JCSPNetworkException("Failed to resolve channel named: " + name);
        }
Example #8
0
 public void NetChannelRequestFailed(INetNode node, NetChannel channel, ErrorMessage error, Guid requestId, int durationMs)
 {
     if (_logger.IsEnabled(LogEventLevel.Warning))
     {
         _logger.Warning("NetNode {@node} NetChannel {@channel} sent request failed with {@error} for {requestId} in {durationMs} ms", node, channel, error, requestId, durationMs);
     }
 }
Example #9
0
        /**
         * Resolves a name on the BNS, retrieving the NetBarrierLocation for the NetBarrier
         *
         * @param name
         *            The name to resolve from the BNS
         * @return The NetBarrierLocation of the NetBarrier declared with name
         * @//throws JCSPNetworkException
         *             Thrown if something goes wrong in the underlying architecture
         */
        public NetBarrierLocation resolve(String name)
        // //throws JCSPNetworkException
        {
            // Create a temporary channel to receive the incoming NetBarrierLocation
            NetChannelInput responseChan = NetChannel.net2one(new BNSNetworkMessageFilter.FilterRX());

            // Create the resolution message
            BNSMessage message = new BNSMessage();

            message.type            = BNSMessageProtocol.RESOLVE_REQUEST;
            message.serviceLocation = (NetChannelLocation)responseChan.getLocation();
            message.name            = name;

            // Write resolution message to the BNS
            this.toBNS.write(message);

            // Read in reply
            BNSMessage reply = (BNSMessage)responseChan.read();

            // Destroy temporary channel
            responseChan.destroy();

            // Return result
            if (reply.success)
            {
                return(reply.location);
            }
            throw new JCSPNetworkException("Failed to resolve barrier named: " + name);
        }
Example #10
0
        public override void ChannelRead(IChannelHandlerContext context, object message)
        {
            var    byteBuffer = message as IByteBuffer;
            string localIP    = "";
            int    localPort  = 0;
            string remoteIP   = "";
            int    remotePort = 0;

            if (byteBuffer != null)
            {
                IPEndPoint iPEndPoint = context.Channel.LocalAddress as IPEndPoint;
                if (iPEndPoint != null)
                {
                    localIP   = iPEndPoint.Address.ToString();
                    localPort = iPEndPoint.Port;
                }
                iPEndPoint = context.Channel.RemoteAddress as IPEndPoint;
                if (iPEndPoint != null)
                {
                    remoteIP   = iPEndPoint.Address.ToString();
                    remotePort = iPEndPoint.Port;
                }
            }
            NetChannel netSocket = new NetChannel()
            {
                recData = byteBuffer.Array, localIP = localIP, localPort = localPort, remoteIP = remoteIP, remotePort = remotePort
            };

            this.nettyUDPClient.AddData(netSocket);
        }
Example #11
0
        /// <summary>
        /// Broadcasts a message to all connections except specified; should NOT be used for
        /// messages which uses the string table read/write methods!
        /// </summary>
        public int Broadcast(NetMessage msg, NetChannel channel, NetConnection except)
        {
            int  numSentTo    = 0;
            bool originalSent = false;

            foreach (NetConnection conn in Connections)
            {
                if (conn == null || conn == except || (conn.Status != NetConnectionStatus.Connected && conn.Status != NetConnectionStatus.Reconnecting))
                {
                    continue;
                }

                numSentTo++;

                if (!originalSent)
                {
                    // send original
                    conn.SendMessage(msg, channel);
                    originalSent = true;
                }
                else
                {
                    // send refcloned message
                    NetMessage clone = NetMessage.CreateReferenceClone(msg);
                    conn.SendMessage(clone, channel);
                    numSentTo++;
                }
            }

            return(numSentTo);
        }
Example #12
0
        /**
         * Creates a new BNSService
         *
         * @param bnsNode
         *            The Node that the BNS is on
         * @//throws JCSPNetworkException
         *             Thrown if something goes wrong in the underlying architecture
         */
        public BNSService(NodeID bnsNode)
        // //throws JCSPNetworkException
        {
            // Create input and output end
            this.toBNS   = NetChannel.one2net(bnsNode, 2, new BNSNetworkMessageFilter.FilterTX());
            this.fromBNS = NetChannel.net2one(new BNSNetworkMessageFilter.FilterRX());

            // Logon to the BNS
            BNSMessage message = new BNSMessage();

            message.type            = BNSMessageProtocol.LOGON_MESSAGE;
            message.serviceLocation = (NetChannelLocation)this.fromBNS.getLocation();
            this.toBNS.write(message);

            // Wait for logon reply message
            BNSMessage logonReply = (BNSMessage)this.fromBNS.read();

            // Check if we logged on OK
            if (logonReply.success == false)
            {
                Node.err.log(this.GetType(), "Failed to logon to BNS");
                throw new JCSPNetworkException("Failed to logon to BNS");
            }
            Node.log.log(this.GetType(), "Logged into BNS");
        }
    /// <summary>
    /// Send packet to all from list
    /// </summary>
    public void SendPacketToAllFromListJob
    (
        ulong[] list,
        RakNet_Packet packet,
        PacketPriority priority       = PacketPriority.IMMEDIATE_PRIORITY,
        PacketReliability reliability = PacketReliability.RELIABLE,
        NetChannel channel            = NetChannel.NET_EVENTS
    )
    {
        if (server_peer.state != PeerState.RunAsServer)
        {
            return;
        }


        if (!packet.begin_write || !packet.end_write)
        {
            Debug.LogError("Can't send packet! Check Begin & End packet");
            return;
        }

        _SendPacketToAllJob a = new _SendPacketToAllJob();

        a.peer  = (ulong)server_peer.ptr;
        a.p     = priority;
        a.r     = reliability;
        a.c     = channel;
        a.array = new NativeArray <ulong>(list, Allocator.TempJob);

        JobHandle jobHandle = a.Schedule(list.Length, 64);

        jobHandle.Complete();

        a.array.Dispose();
    }
        public void SendTo(Message msg, NetChannel channel, int destinationClientID)
        {
            if ((!ActiveConnections.ContainsKey(destinationClientID)) || (ActiveConnections[destinationClientID].Status != NetConnectionStatus.Connected))
                throw new System.InvalidOperationException("Not a valid player");

            _serverMessageSender.SendTo(msg, channel, ActiveConnections[destinationClientID]);
        }
    /// <summary>
    /// Send packet to all
    /// </summary>
    public void SendPacketToAll
    (
        RakNet_Packet packet,
        PacketPriority priority       = PacketPriority.IMMEDIATE_PRIORITY,
        PacketReliability reliability = PacketReliability.RELIABLE,
        NetChannel channel            = NetChannel.NET_EVENTS
    )
    {
        if (server_peer.state != PeerState.RunAsServer)
        {
            return;
        }


        if (!packet.begin_write || !packet.end_write)
        {
            Debug.LogError("Can't send packet! Check Begin & End packet");
            return;
        }


        for (int i = 0; i < connections.Count; i++)
        {
            server_peer.SendToClient(connections[i].guid, priority, reliability, channel);
        }
    }
        protected override void OnStopped()
        {
            NetChannel.RemoveRemoteEvent("Client_GamemodeInfo");
            NetChannel.RemoveRemoteEvent("Client_UpdateScores");
            NetChannel.RemoveRemoteEvent("Client_IntelPickedUp");
            NetChannel.RemoveRemoteEvent("Client_IntelDropped");
            NetChannel.RemoveRemoteEvent("Client_IntelCaptured");
            NetChannel.RemoveRemoteEvent("Client_IntelReturned");

            objectComponent.RemoveInstantiationEvent("Client_CreateIntel");
            objectComponent.RemoveInstantiationEvent("Client_CreateCommandPost");

            redIntel  = null;
            blueIntel = null;
            redPost   = null;
            bluePost  = null;

            TeamAScore = 0;
            TeamBScore = 0;
            ScoreCap   = 3;

            OurPlayerHasIntel = false;

            intelAudioSource?.Dispose();

            base.OnStopped();
        }
 public void SendToServer(PacketPriority priority, PacketReliability reliability, NetChannel channel)
 {
     if (ptr != IntPtr.Zero)
     {
         NETSND_Send(ptr, guid, (int)priority, (int)reliability, (int)channel);
     }
 }
Example #18
0
        public static int SendPacket(NetChannel channel, Socket socket, EndPoint to, byte[] data)
        {
            var len = 0;

            try {
                len = socket.SendTo(data, SocketFlags.None, to);
            } catch (SocketException e) {
                if (e.SocketErrorCode == SocketError.WouldBlock)
                {
                    return(0);
                }

                if (e.SocketErrorCode == SocketError.ConnectionReset)
                {
                    return(0);
                }

                if (e.SocketErrorCode == SocketError.AddressNotAvailable)
                {
                    return(0);
                }
            }

            return(len);
        }
        static void Main(string[] args)
        {
            Console.WriteLine("Successor Starts!");
            //This Process runs after Delta

            Console.WriteLine("Please enter IP address for this node.");
            var successorNodeIP = Console.ReadLine();

            Console.WriteLine("Please enter IP address for Prefix.");
            var prefixNodeIP = Console.ReadLine();


            var successorNodeAddr = new TCPIPNodeAddress(successorNodeIP, 3000);

            Node.getInstance().init(successorNodeAddr);
            var delta2sucessor = NetChannel.net2one();

            var prefixNodeAddr   = new TCPIPNodeAddress(prefixNodeIP, 3000);
            var successor2prefix =
                NetChannel.one2net(prefixNodeAddr, 51); //channel number 50 is already taken for delta2prefix

            Console.WriteLine("successor2prefix location = " + successor2prefix.getLocation().ToString());

            //write to prefix successor is running so it can notify delta about it
            successor2prefix.write(0);

            Console.WriteLine("Network is good to run. Please refer to Consume process window");
            new CSPParallel(
                new IamCSProcess[]
            {
                new Successor(delta2sucessor, successor2prefix)
            }
                ).run();
        }
        public NetworkP2PMessage(NetworkFlags flags, string name, InternalCode internCode)
        {
            this.flags = flags;

            // TODO: optimize by calculating initial buffer size by bit-flags & args

            // TODO: remove the default 4 bytes allocated by the default NetBuffer constructor.

            stream = new BitStream(isTypeSafe);
            var buffer = stream._buffer;

            connection = null;
            channel    = (isReliable) ? NetChannel.ReliableInOrder1 : NetChannel.Unreliable;

            this.name       = name;
            this.internCode = internCode;

            // write header to stream:

            HeaderFlags headerFlags = (HeaderFlags)internCode;

            if (isTypeSafe)
            {
                headerFlags |= HeaderFlags.IsTypeSafe;
            }

            buffer.Write((byte)headerFlags);

            if (internCode == InternalCode.None)
            {
                buffer.Write(name);
            }

            buffer.PositionBits = buffer.LengthBits;
        }
Example #21
0
        public override void OnPlayerKilled(ServerMPPlayer killer, NetworkPlayer killerNetPlayer,
                                            ServerMPPlayer assistant, NetworkPlayer assistantNetPlayer,
                                            ServerMPPlayer killed, NetworkPlayer killedNetPlayer, string item)
        {
            // Update scores
            if (killer == null)
            {
                // Update killed score
                killedNetPlayer.Score += SCORE_SUICIDE_PENALTY;
            }
            else
            {
                // Update killer score
                if (killer.Team == killed.Team)
                {
                    killerNetPlayer.Score += SCORE_TEAMKILL_PENALTY;
                }
                else
                {
                    killerNetPlayer.Score += SCORE_KILL;
                }

                // Update assistant score
                if (assistant != null)
                {
                    if (assistant.Team == killed.Team)
                    {
                        assistantNetPlayer.Score += SCORE_ASSIST_TEAMKILL_PENALTY;
                    }
                    else
                    {
                        assistantNetPlayer.Score += SCORE_ASSIST;
                    }
                }

                // Update team scores
                if (killer.Team != killed.Team)
                {
                    if (killer.Team == Team.A)
                    {
                        teamAScore++;
                    }
                    else if (killer.Team == Team.B)
                    {
                        teamBScore++;
                    }
                }

                // Announce score change
                NetChannel.FireEventForAllConnections("Client_UpdateScores", RemoteFlag.None,
                                                      NetDeliveryMethod.ReliableOrdered, (short)teamAScore, (short)teamBScore);
            }

            base.OnPlayerKilled(killer, killerNetPlayer, assistant, assistantNetPlayer,
                                killed, killedNetPlayer, item);

            // Add player to the respawn list
            AddRespawn(killed.StateInfo.Owner, RESPAWN_TIME);
        }
 /// <summary>
 /// Sends a message using the specified channel; takes ownership of the NetBuffer, don't reuse it after this call
 /// </summary>
 public void SendMessage(NetBuffer data, NetChannel channel)
 {
     if (m_serverConnection == null || m_serverConnection.Status != NetConnectionStatus.Connected)
     {
         throw new NetException("You must be connected first!");
     }
     m_serverConnection.SendMessage(data, channel);
 }
Example #23
0
        internal void AdvanceExpected(NetChannel channel, int add)
        {
            int seqChan = (int)channel;
            int cur     = m_expectedSequenceNumbers[seqChan];

            cur = (cur + add) % NetConstants.NumSequenceNumbers;
            m_expectedSequenceNumbers[seqChan] = cur;
        }
Example #24
0
        public override void FullConnect(EndPoint addr)
        {
            base.FullConnect(addr);

            NetChannel.SetDataRate(Program.ClRate);

            Console.WriteLine("Connected to {0}", addr);
        }
 /// <summary>
 /// Sends a message to a specific connection
 /// </summary>
 public void SendMessage(NetBuffer data, NetConnection recipient, NetChannel channel)
 {
     if (recipient == null)
     {
         throw new ArgumentNullException("recipient");
     }
     recipient.SendMessage(data, channel);
 }
Example #26
0
 public BaseClientState()
 {
     NetChannel    = null;
     _socket       = null;
     _challengeNr  = 0;
     _retryNumber  = 0;
     _retryAddress = null;
     SignonState   = ESignonState.None;
 }
Example #27
0
 public void AddQueMsg(NetBuffer buff, NetChannel chan)
 {
     lock (Que)
     {
         Que.Add(new qmsg(buff, chan));
         msgs++;
     }
     WH.Set();
 }
Example #28
0
 internal static void Run(string host, int port, int mps, int throttle, NetChannel channel)
 {
     s_client.Configuration.ThrottleBytesPerSecond = throttle;
     s_client.Connect(host, port, null);
     s_messagesPerSecond = mps;
     s_oneMessageTime    = 1.0 / (double)mps;
     s_sentUntil         = NetTime.Now;
     m_sendOnChannel     = channel;
 }
        protected override void OnStarted()
        {
            NetChannel.AddRemoteEvent("Client_GamemodeInfo", R_GamemodeInfo);
            NetChannel.AddRemoteEvent("Client_UpdateScores", R_UpdateScores);

            objectComponent.AddInstantiationEvent("Client_CreateCommandPost", I_CreateCommandPost);

            base.OnStarted();
        }
Example #30
0
 public virtual void ConnectionStart(NetChannel netChannel)
 {
     netChannel.RegisterMessage(new NetMessageTick {
         ChannelHandler = this
     });
     netChannel.RegisterMessage(new NetMessageSignonState {
         ChannelHandler = this
     });
 }
Example #31
0
        public void SendData(NetChannel netChannel, byte[] data)
        {
            IChannel channel = netChannel.channel as IChannel;

            if (channel != null)
            {
                channel.WriteAndFlushAsync(data);
            }
        }
    protected virtual void Awake()
    {
        networkObjectManager = GetComponent <NetworkObjectManager>();
        playerManager        = new PlayerManager();
        netChannel           = new NetChannel(debugNetworkSettings);

        netChannel.PeerConnectedHandler    += OnPeerConnected;
        netChannel.PeerDisconnectedHandler += OnPeerDisconnected;
    }
Example #33
0
        static void Main(string[] args)
        {
            Console.WriteLine("Delta Starts!");
            //This process starts after Prefix


            Console.WriteLine("Please enter IP address for this node.");
            var deltaNodeIP = Console.ReadLine();

            Console.WriteLine("Please enter IP address for Prefix.");
            var prefixNodeIP = Console.ReadLine();

            Console.WriteLine("Please enter IP address for Consume.");
            var consumeNodeIP = Console.ReadLine();

            Console.WriteLine("Please enter IP address for Successor.");
            var successorNodeIP = Console.ReadLine();

            var deltaNodeAddr = new TCPIPNodeAddress(deltaNodeIP, 3000);

            Node.getInstance().init(deltaNodeAddr);
            var prefix2delta = NetChannel.net2one();

            //we need to notify prefix that delta exists before it can connect to it
            var prefixNodeAddr = new TCPIPNodeAddress(prefixNodeIP, 3000);
            var delta2prefix   = NetChannel.one2net(prefixNodeAddr, 50);

            delta2prefix.write(0); //notify prefix delta is ready


            var consumeNodeAddr = new TCPIPNodeAddress(consumeNodeIP, 3300);
            var delta2consume   = NetChannel.one2net(consumeNodeAddr, 50);

            //first write to the consume to make sure network works
            delta2consume.write(0);


            //Please start successor process now
            Console.WriteLine("Please start successor process now");
            prefix2delta.read(); //when the signal from prefix comes back it means successor is already running

            var successorNodeAddr = new TCPIPNodeAddress(successorNodeIP, 3000);
            var delta2successor   = NetChannel.one2net(successorNodeAddr, 50);

            Console.WriteLine("delta2consume location = " + delta2consume.getLocation().ToString());
            Console.WriteLine("delta2successor location = " + delta2successor.getLocation().ToString());

            Console.WriteLine("\nNetwork is good to run. Please refer to Consume process window");


            new CSPParallel(
                new IamCSProcess[]
            {
                new Delta2(prefix2delta, delta2consume, delta2successor)
            }
                ).run();
        }
Example #34
0
 // Broadcast a message to logged in players, except the id player (if id = -1, no player is ignored)
 public void BroadcastMsgExcept(NetMessage msg, NetChannel channel, int id)
 {
    IDictionaryEnumerator en = PList.GetPlayerEnum();
    while (en.MoveNext())
    {
       if (((Player)en.Value).Carac.ActorID != id)
          Server.SendMessage(msg, ((Player)en.Value).Connection, channel);
    }
 }
        public void Send(Message msg, NetChannel channel)
        {
            if (_netClient.Status != NetConnectionStatus.Connected)
                throw new System.InvalidOperationException("Client not connected to server");

            var buffer = _netClient.CreateBuffer();
            buffer.Write(msg);

            _netClient.SendMessage(buffer, channel);

            _logger.Debug("Sent Message with " + msg.Items.Count + " items and total length " + buffer.Data.Length + " bytes to the server.");
        }
        static void Main(string[] args)
        {
            //configure serialization
            var messageSerializer = new ProtobufMessageSerializer(
                new Message[] {new JoinRoom(), new Say(), new RoomEvent(), new JoinRoomResponse()},
                new MessageHeader[] {new OperationHeader()});

            var logger = new LoggerConfiguration()
                .ConfigureMOUSETypesDestructure()
                .MinimumLevel.Verbose()
                .WriteTo.ColoredConsole()
                .CreateLogger();

            var coreEventLogger = new SerilogCoreEvents(logger);

            //configure network transport provider
            var transport = new LidgrenNetProvider(
                new NetPeerConfiguration("Public") { LocalAddress = IPAddress.Loopback },
                new SerilogLidgrenEvents(logger));
            var config = new NetNodeConfig {SendTimeoutSec = 30, ConnectTimeoutSec = 60};


            var node = new NetNode<NetChannel>("client", transport, coreEventLogger, messageSerializer,config : config, 
                channelFactory: (n,transportChannel) =>
                {
                    var peer = new NetChannel(n, transportChannel, messageSerializer, coreEventLogger, config, new WcfBufferPool());
                    //low level channel handling declaration uses Rx channel.OperationReceivedEvent under the hood
                    peer.RegisterHandler<RoomEvent>(msg => Console.WriteLine(msg.UserName + "->" + msg.Text));

                    return peer;
                });

            try
            {
                Run(node).Wait();
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.ToString());
            }
            Console.ReadKey();
        }
Example #37
0
 public void Broadcast(NetBuffer msg, NetChannel channel)
 {
     NetHost.Broadcast(msg, channel);
 }
Example #38
0
		public void AssignSequenceNumber(NetMessage msg, NetChannel channel)
		{
			if (msg == null)
				throw new ArgumentNullException("msg");
			int chanNr = (int)channel;
			lock (m_nextSequenceNumber)
			{
				msg.SequenceChannel = channel;
				msg.SequenceNumber = m_nextSequenceNumber[chanNr]++;
				if (m_nextSequenceNumber[chanNr] >= NetConstants.NumSequenceNumbers)
					m_nextSequenceNumber[chanNr] = 0;
			}
			return;
		}
Example #39
0
 public virtual void SendMessage( NetConnection to, NetBuffer message, NetChannel channel )
 {
     PendingSend msg = new PendingSend();
     msg.message = ProcessOutboundMessage(to,message);
     msg.to = to;
     msg.channel = channel;
     lock(PendingSends)
     {
         PendingSends.Add(msg);
     }
 }
Example #40
0
		/// <summary>
		/// Broadcasts a message to all connections except specified; should NOT be used for
		/// messages which uses the string table read/write methods!
		/// </summary>
		public int Broadcast(NetMessage msg, NetChannel channel, NetConnection except)
		{
			int numSentTo = 0;
			bool originalSent = false;
			foreach (NetConnection conn in Connections)
			{
				if (conn == null || conn == except || (conn.Status != NetConnectionStatus.Connected && conn.Status != NetConnectionStatus.Reconnecting))
					continue;

				numSentTo++;

				if (!originalSent)
				{
					// send original
					conn.SendMessage(msg, channel);
					originalSent = true;
				}
				else
				{
					// send refcloned message
					NetMessage clone = NetMessage.CreateReferenceClone(msg);
					conn.SendMessage(clone, channel);
					numSentTo++;
				}
			}

			return numSentTo;
		}
Example #41
0
 /// <summary>
 /// Sends a message to all connections to this server, except 'exclude'
 /// </summary>
 public void SendToAll(NetBuffer data, NetChannel channel, NetConnection exclude)
 {
     lock (m_connections)
     {
         foreach (NetConnection conn in m_connections)
         {
             if (conn.Status == NetConnectionStatus.Connected && conn != exclude)
                 conn.SendMessage(data, channel);
         }
     }
 }
Example #42
0
 /// <summary>
 /// Sends a message to a specific connection
 /// </summary>
 public void SendMessage(NetBuffer data, NetConnection recipient, NetChannel channel)
 {
     if (recipient == null)
         throw new ArgumentNullException("recipient");
     recipient.SendMessage(data, channel);
 }
		internal void AdvanceExpected(NetChannel channel, int add)
		{
			int seqChan = (int)channel;
			int cur = m_expectedSequenceNumbers[seqChan];
			cur = (cur + add) % NetConstants.NumSequenceNumbers;
			m_expectedSequenceNumbers[seqChan] = cur;
		}
Example #44
0
 /// <summary>
 /// Sends a message using the specified channel
 /// </summary>
 public void SendMessage(NetBuffer data, NetChannel channel)
 {
     if (m_serverConnection == null || m_serverConnection.Status != NetConnectionStatus.Connected)
         throw new NetException("You must be connected first!");
     m_serverConnection.SendMessage(data, channel);
 }
Example #45
0
 /// <summary>
 /// Sends a message using the specified channel, with the specified data as receipt
 /// </summary>
 public void SendMessage(NetBuffer data, NetChannel channel, NetBuffer receipt)
 {
     if (m_serverConnection == null || m_serverConnection.Status != NetConnectionStatus.Connected)
         throw new NetException("You must be connected first!");
     if ((m_enabledMessageTypes & NetMessageType.Receipt) != NetMessageType.Receipt)
         LogVerbose("Warning; Receipt messagetype is not enabled!");
     m_serverConnection.SendMessage(data, channel, receipt);
 }
Example #46
0
 public qmsg(NetBuffer buff, NetChannel chan)
 {
     Buffer = buff;
     Channel = chan;
 }
Example #47
0
		internal void SendMessage(NetMessage msg, NetChannel channel)
		{
			if (msg.Length > m_parent.Configuration.MaximumTransmissionUnit)
			{
				// fragment large message
				int totlen = msg.Length;
				int splitSize = m_parent.Configuration.MaximumTransmissionUnit - 13; // todo: research this number
				int numFragments = totlen / splitSize;
				if (numFragments * splitSize < totlen)
					numFragments++;
				
				byte hdr1 = (byte)numFragments;
				byte hdr2 = (byte)(numFragments >> 8);

				int ptr = 0;
				for (int i = 0; i < numFragments; i++)
				{
					int numBytes = msg.Length - ptr;
					if (numBytes > splitSize)
						numBytes = splitSize;
					byte[] fragmentData = new byte[5 + numBytes];
					fragmentData[0] = m_nextFragmentAssemblyId;
					fragmentData[1] = hdr1;
					fragmentData[2] = hdr2;
					fragmentData[3] = (byte)i;
					fragmentData[4] = (byte)(i >> 8);
					Buffer.BlockCopy(msg.m_buffer.Data, ptr, fragmentData, 5, numBytes);

					// send fragment
					NetMessage fragment = new NetMessage(NetMessageType.UserFragmented, fragmentData);
					SendMessage(fragment, channel);

					ptr += numBytes;
				}
				//m_parent.Log.Debug("Sent " + numFragments + " fragments, " + splitSize + " bytes per fragment = " + totlen);
				m_nextFragmentAssemblyId++;
				return;
			}

			msg.SequenceChannel = channel;
			AssignSequenceNumber(msg, channel);
			m_unsentMessages.Enqueue(msg);
		}
		public long GetUserMessagesSent(NetChannel channel)
		{
			return m_userTypeMessagesSent[(int)channel];
		}
Example #49
0
        /// <summary>
        /// Sends a message to the server using a specified channel
        /// </summary>
        public bool SendMessage(NetMessage msg, NetChannel channel)
        {
            if (m_serverConnection == null || m_serverConnection.Status == NetConnectionStatus.Disconnected)
            {
                Log.Warning("SendMessage failed - Not connected!");
                return false;
            }

            m_serverConnection.SendMessage(msg, channel);
            return true;
        }
Example #50
0
 /// <summary>
 /// Sends the given message using the given UDP delivery type.  A client will send to the server, a server will broadcast.
 /// </summary>
 /// <param name="message">The message to be sent</param>
 /// <param name="deliveryType">The UDP delivery type</param>
 public void SendMessage(SpiderMessage message, NetChannel deliveryType)
 {
     NetMessage msg = new NetMessage();
     msg.Write(message.ToByteArray());
     spiderNet.SendMessage(msg, deliveryType);
 }
Example #51
0
        /// <summary>
        /// Sends a message to the specified connections; takes ownership of the NetBuffer, don't reuse it after this call
        /// </summary>
        public void SendMessage(NetBuffer data, IEnumerable<NetConnection> recipients, NetChannel channel)
        {
            if (recipients == null)
                throw new ArgumentNullException("recipients");

            foreach (NetConnection recipient in recipients)
                recipient.SendMessage(data, channel);
        }
Example #52
0
		/// <summary>
		/// Queue message for sending
		/// </summary>
		public void SendMessage(NetBuffer data, NetChannel channel)
		{
			SendMessage(data, channel, null, false);
		}
Example #53
0
		/// <summary>
		/// Broadcasts a message to all connections; should NOT be used for messages which
		/// uses the string table read/write methods!
		/// </summary>
		public int Broadcast(NetMessage msg, NetChannel channel)
		{
			return SendMessage(msg, Connections, channel);
		}
Example #54
0
		/// <summary>
		/// Queue a reliable message for sending. When it has arrived ReceiptReceived will be fired on owning NetBase, and the ReceiptEventArgs will contain the object passed to this method.
		/// </summary>
		public void SendMessage(NetBuffer data, NetChannel channel, NetBuffer receiptData)
		{
			SendMessage(data, channel, receiptData, false);
		}
Example #55
0
		/// <summary>
		/// Sends a message to several connections using the channel specified; should NOT be
		/// used for messages which uses the string table read/write methods!
		/// </summary>
		/// <returns>number of messages sent</returns>
		public int SendMessage(NetMessage msg, IEnumerable<NetConnection> connections, NetChannel channel)
		{
			if (connections == null)
				throw new ArgumentNullException("connection");

			int numSentTo = 0;
			bool originalSent = false;
			foreach (NetConnection connection in connections)
			{
				if (connection == null || (connection.Status != NetConnectionStatus.Connected && connection.Status != NetConnectionStatus.Reconnecting))
					continue;

				if (!originalSent)
				{
					connection.SendMessage(msg, channel);
					originalSent = true;
				}
				else
				{
					// send refcloned message
					NetMessage clone = NetMessage.CreateReferenceClone(msg);
					connection.SendMessage(clone, channel);
				}
				numSentTo++;
			}

			// Log.Debug("Broadcast to " + numSentTo + " connections...");

			return numSentTo;
		}
Example #56
0
		// TODO: Use this with TRUE isLibraryThread for internal sendings (acks etc)

		internal void SendMessage(NetBuffer data, NetChannel channel, NetBuffer receiptData, bool isLibraryThread)
		{
			if (m_status != NetConnectionStatus.Connected)
				throw new NetException("Status must be Connected to send messages");

			if (data.LengthBytes > m_owner.m_config.m_maximumTransmissionUnit)
			{
				//
				// Fragmented message
				//

				int dataLen = data.LengthBytes;
				int chunkSize = m_owner.m_config.m_maximumTransmissionUnit - 10; // header
				int numFragments = dataLen / chunkSize;
				if (chunkSize * numFragments < dataLen)
					numFragments++;

				ushort fragId = m_nextSendFragmentId++;

				for (int i = 0; i < numFragments; i++)
				{
					OutgoingNetMessage fmsg = m_owner.CreateOutgoingMessage();
					fmsg.m_type = NetMessageLibraryType.UserFragmented;
					fmsg.m_msgType = NetMessageType.Data;

					NetBuffer fragBuf = m_owner.CreateBuffer();
					fragBuf.Write(fragId);
					fragBuf.WriteVariableUInt32((uint)i);
					fragBuf.WriteVariableUInt32((uint)numFragments);

					if (i < numFragments - 1)
					{
						// normal fragment
						fragBuf.Write(data.Data, i * chunkSize, chunkSize);
					}
					else
					{
						// last fragment
						int bitsInLast = data.LengthBits - (chunkSize * (numFragments - 1) * 8);
						int bytesInLast = dataLen - (chunkSize * (numFragments - 1));
						fragBuf.Write(data.Data, i * chunkSize, bytesInLast);

						// add receipt only to last message
						fmsg.m_receiptData = receiptData;
					}
					fmsg.m_data = fragBuf;
					fmsg.m_data.m_refCount = 1; // since it's just been created

					fmsg.m_numSent = 0;
					fmsg.m_nextResend = double.MaxValue;
					fmsg.m_sequenceChannel = channel;
					fmsg.m_sequenceNumber = -1;

					if (isLibraryThread)
					{
						m_unsentMessages.Enqueue(fmsg);
					}
					else
					{
						lock (m_lockedUnsentMessages)
							m_lockedUnsentMessages.Enqueue(fmsg);
					}
				}

				// TODO: recycle the original, unfragmented data

				return;
			}

			//
			// Normal, unfragmented, message
			//

			OutgoingNetMessage msg = m_owner.CreateOutgoingMessage();
			msg.m_msgType = NetMessageType.Data;
			msg.m_type = NetMessageLibraryType.User;
			msg.m_data = data;
			msg.m_data.m_refCount++; // it could have been sent earlier also
			msg.m_numSent = 0;
			msg.m_nextResend = double.MaxValue;
			msg.m_sequenceChannel = channel;
			msg.m_sequenceNumber = -1;
			msg.m_receiptData = receiptData;

			if (isLibraryThread)
			{
				m_unsentMessages.Enqueue(msg);
			}
			else
			{
				lock (m_lockedUnsentMessages)
					m_lockedUnsentMessages.Enqueue(msg);
			}
		}
Example #57
0
 public virtual void Broadcast(NetBuffer data, NetChannel channel)
 {
     PendingSend msg = new PendingSend();
     msg.message = ProcessOutboundMessage(null, data);
     msg.to = null;
     msg.channel = channel;
     lock (PendingSends)
     {
         PendingSends.Add(msg);
     }
 }
		internal void CountMessageReceived(NetMessageLibraryType tp, NetChannel channel, int numBytes, double now)
		{
			m_messagesReceived++;
			if (tp == NetMessageLibraryType.User)
			{
				m_userMessagesReceived++;
				m_userBytesReceived += (4 + numBytes);
				m_userTypeMessagesReceived[(int)channel]++;
			}

			NetConnectionStatistics window = GetCurrentWindow(now);
			if (window != null)
				window.CountMessageReceived(tp, channel, numBytes, now);
		}
		public long GetUserMessagesReceived(NetChannel channel)
		{
			return m_userTypeMessagesReceived[(int)channel];
		}
Example #60
0
		internal static void Run(string host, int port, int mps, int throttle, NetChannel channel)
		{
			s_client.Configuration.ThrottleBytesPerSecond = throttle;
			s_client.Connect(host, port, null);
			s_messagesPerSecond = mps;
			s_oneMessageTime = 1.0 / (double)mps;
			s_sentUntil = NetTime.Now;
			m_sendOnChannel = channel;
		}