Ejemplo n.º 1
0
        protected readonly Tensor Wxh; // each column is a neuron

        public DenseUnit(NetBase net, int inputDim, int outputDim)
        {
            _net = net;
            Wxh  = new Tensor(inputDim, outputDim, new GlorotNormalInit(_net, inputDim, outputDim));
            Bh   = new Tensor(1, outputDim, null);
            SubmitParameters(net);
        }
Ejemplo n.º 2
0
 public void End()
 {
     if (parent != null)
     {
         //==
         head_data          = null;
         parent             = null;
         buffer             = null;
         ConnectResultEvent = null;
         DisConnectEvent    = null;
         //==
         if (socket != null)
         {
             try
             {
                 socket.Close();
             }
             catch (Exception)
             {
             }
             socket = null;
         }
         //==
         if (recvThraed != null)
         {
             recvThraed.Abort();
             recvThraed = null;
         }
     }
 }
Ejemplo n.º 3
0
 public GlorotNormalInit(NetBase net, int fanIn, int fanOut)
 {
     _net    = net;
     _fanIn  = fanIn;
     _fanOut = fanOut;
     _factor = (float)Math.Sqrt(6.0f / (fanIn + fanOut));
 }
Ejemplo n.º 4
0
        // build a model
        private void InitNet(NetType netType)
        {
            var eDim = _dataset.Examples[0].Feature.Length;
            var oDim = _conf.LabelCount;

            switch (netType)
            {
            case NetType.mlp:
                Net = new MLP(_conf, eDim, oDim, Opt);
                break;

            case NetType.mlptop:
                Net = new MLPTop(_conf, eDim, oDim, Opt);
                break;

            case NetType.mlprand:
                Net = new MLPRand(_conf, eDim, oDim, Opt);
                break;

            case NetType.mlpvar:
                Net = new MLPVar(_conf, eDim, oDim, Opt);
                break;

            default:
                // should never reach this
                throw new ArgumentOutOfRangeException(nameof(netType), netType, null);
            }
        }
        public (object Instance, int BytesParsed) ObjectFromBytes(byte[] data, int length, Type type)
        {
            Type elementType = type.GetElementType();

            if (!ParentModule.HasConverterOfType(elementType))
            {
                NetBase.WriteDebug($"Invalid element type in array conversion! ({elementType})", true);
            }

            //The 'length' parameter here is used to determine how many bytes at the start of the array are for the length of the string data
            (ushort Instance, int BytesParsed)t = ParentModule.ObjectFromBytes <ushort>(data);

            ushort arraySize = t.Instance;

            byte[] arrayBytes = data.Skip(t.BytesParsed).ToArray();

            Array instances = Array.CreateInstance(elementType, arraySize);

            int parsed = t.BytesParsed;

            for (int i = 0; i < arraySize; ++i)
            {
                (object Instance, int BytesParsed)instanceTuple = ParentModule.ObjectFromBytes(elementType, arrayBytes, t.BytesParsed);
                instances.SetValue(instanceTuple.Instance, i);
                parsed    += instanceTuple.BytesParsed;
                arrayBytes = arrayBytes.Skip(instanceTuple.BytesParsed).ToArray();
            }

            return(instances, parsed);
        }
Ejemplo n.º 6
0
    public void Button_Connect_OnClick()
    {
        string IP = text_Connect.text;

        netBase = netClient = new NetClient();
        netClient.Connect(IP);
    }
Ejemplo n.º 7
0
 public TcpClient(NetBase _parent)
 {
     BufferSize  = BufferSize * 5;
     this.buffer = new byte[BufferSize];
     parent      = _parent;
     head_data   = new byte[20];
 }
Ejemplo n.º 8
0
    public bool Send(byte[] buffer, ushort option)
    {
        if (buffer.Length < 0)
        {
            return(false);
        }
        if (buffer.Length + NetBase.NET_HEADER_SIZE > NetBase.NET_BUFF_SIZE)
        {
            return(false);
        }

        if (sentNumber < 1)
        {
            sentNumber++;
        }

        NetPacket np = new NetPacket();

        np.header.netId    = NetBase.NET_ID;
        np.header.option   = option;
        np.header.number   = sentNumber++;
        np.header.checksum = (ushort)NetBase.ComputeChecksum(buffer);
        np.data            = buffer;

        m_sendingPacks.Add(np);

        return(true);
    }
Ejemplo n.º 9
0
    public int Send(NetPacket packet, EndPoint destination)
    {
        if (packet.data != null && packet.data.Length > 0)
        {
            int    size   = NetBase.NET_HEADER_SIZE + packet.data.Length;
            byte[] buffer = new byte[size];

            // copy header information
            Buffer.BlockCopy(NetBase.NetHeaderToByteArray(packet.header), 0, buffer, 0, NetBase.NET_HEADER_SIZE);

            // copy data to the buffer
            Buffer.BlockCopy(packet.data, 0, buffer, NetBase.NET_HEADER_SIZE, packet.data.Length);

            return(Send(buffer, destination));
        }
        else
        {
            int    size   = NetBase.NET_HEADER_SIZE;
            byte[] buffer = new byte[size];

            // copy header information
            Buffer.BlockCopy(NetBase.NetHeaderToByteArray(packet.header), 0, buffer, 0, NetBase.NET_HEADER_SIZE);

            return(Send(buffer, destination));
        }
    }
Ejemplo n.º 10
0
 public void EndNetWork()
 {
     if (network != null)
     {
         network.End();
         network = null;
     }
 }
Ejemplo n.º 11
0
 public DenseUnit(NetBase net, int inputDim, int outputDim, RNG r)
 {
     _wxh = new Tensor(outputDim, inputDim, new GlorotNormalInit(inputDim, outputDim, r));
     _bh  = new Tensor(outputDim, 1, null);
     //_wxh = new Tensor(outputDim, inputDim, new TruncatedNormalInit(0.1));
     //_bh = new Tensor(outputDim, 1, new IdentityInit(0.1));
     net.AddParam(_wxh);
     net.AddParam(_bh);
 }
Ejemplo n.º 12
0
        internal void _Apply(NetBase net)
        {
            if (net == null)
            {
                return;
            }

            net.Simulate(_chanceOfLoss, _chanceOfDuplicates, _minLatency, Math.Max(0, _maxLatency - _minLatency));
            net.Configuration.ThrottleBytesPerSecond = _maxBandwidth * 1024;
        }
Ejemplo n.º 13
0
        public void AddConverter(IByteConverterModule converter)
        {
            if (HasConverterOfType(converter.T))
            {
                NetBase.WriteDebug($"A converter for type {converter.T.FullName} has already been added!", true);
            }

            converter.ParentModule = this;
            knownConverters.Add(converter);
        }
        public (object Instance, int BytesParsed) ObjectFromBytes(byte[] data, int length, Type type)
        {
            Type underlyingType = type.GetEnumUnderlyingType();

            if (!ParentModule.HasConverterOfType(underlyingType))
            {
                NetBase.WriteDebug($"Invalid element type for enum conversion! ({underlyingType})", true);
            }

            return(ParentModule.ObjectFromBytes(underlyingType, data, length));
        }
Ejemplo n.º 15
0
        public void CheckPacket(PacketBase packet, NetBase net)
        {
            switch (packet.PackRealId)
            {
            case PacketS2CLoginResult.PackId: OnPacketLogin(packet as PacketS2CLoginResult); break;

            case PacketS2CRankResult.PackId: OnPacketRankResult(packet as PacketS2CRankResult); break;

            case PacketS2CReplyHeartbeat.PackId: OnPacketReplyHeartbeat(packet as PacketS2CReplyHeartbeat); break;
            }
        }
Ejemplo n.º 16
0
        public byte[] ConvertToBytes(object instance, bool includeLength = true)
        {
            Type instanceType = instance.GetType();

            if (!HasConverterOfType(instanceType))
            {
                NetBase.WriteDebug($"No conversion method exists for type of {instanceType.FullName}!", true);
            }

            return(knownConverters.First(c => c.T == instanceType || c.T == instanceType.BaseType).ConvertToBytes(instance, includeLength));
        }
Ejemplo n.º 17
0
        public static void Main(string[] args)
        {
            NetBase nb = new NetBase();

            nb.Start();

            Console.WriteLine("Server running.\nPress enter to exit.\n");
            Console.ReadLine();

            nb.Stop();
        }
Ejemplo n.º 18
0
    public void AppendReceivedMessage(NetSocket socket, byte[] buffer, int size)
    {
        outTime     = 0;
        isConnected = true;

        NetHeader nh = NetBase.ByteArrayToNetHeader(buffer);

        //	we are waiting for received confirmation from the other side
        if ((nh.option & NetBase.NET_OPTN_CONFIRMED) > 0)
        {
            if (nh.number == confirmNumber && nh.checksum == confirmChecksum)
            {
                Debug.Log("Info: Message number has been confirmed from other side!");

                confirmNumber = 0;  // confirmed
                retryTime     = 0;

                // remove the message from the sending list
                m_sendingPacks.RemoveAt(0);
            }
            else
            {
                // do nothing !!
            }
        }
        else
        {
            //	replay to sender that safe message has been received
            if ((nh.option & NetBase.NET_OPTN_SAFESEND) > 0)
            {
                NetPacket tmp = new NetPacket();
                tmp.header        = nh;
                tmp.header.option = NetBase.NET_OPTN_CONFIRMED;
                socket.Send(tmp, dest);
            }

            //	create message container and append it to the list
            if (nh.number != recvNumber)
            {
                recvNumber = nh.number;

                NetPacket np = new NetPacket();
                np.header = nh;
                np.data   = new byte[size - NetBase.NET_HEADER_SIZE];

                Buffer.BlockCopy(buffer, NetBase.NET_HEADER_SIZE, np.data, 0, np.data.Length);

                //	add it to the received list
                m_receivedPacks.Add(np);

                //sx_print( L"message received header [NO: %d OP: %d CH: %d]\n", np.header.number, np.header.option, np.header.checksum );
            }
        }
    }
Ejemplo n.º 19
0
    static void VerifyRoleHashesAndSendClientList(UdpClient sender, string playerName, string[] roleHashes)
    {
        // TODO: verify the role hashes

        if (roleHashes.Length < LoadedRoleHashes.Count)
        {
            NetBase.WriteDebug($"Received role hash list from {sender.EndPoint as IPEndPoint} \"{playerName}\" has less roles than the server, impossible to verify roles.");
            ConnectedPlayers.Remove(sender.GetPlayer());
            sender.Disconnect();
            return;
        }

        for (int i = 0; i < LoadedRoleHashes.Count; ++i)
        {
            string hash = LoadedRoleHashes[i];
            if (!roleHashes.Contains(hash))
            {
                NetBase.WriteDebug($"Client {sender.EndPoint as IPEndPoint} \"{playerName}\" missing hash {hash} corresponding to role {LoadedRoleTypes.Values.ElementAt(i).AssemblyQualifiedName}!");
                ConnectedPlayers.Remove(sender.GetPlayer());
                sender.Disconnect();
                return;
            }
            else
            {
                NetBase.WriteDebug($"{sender.EndPoint as IPEndPoint}: {hash} {LoadedRoleTypes.Values.ElementAt(i).AssemblyQualifiedName} success!");
            }
        }

        NetWerewolfPlayer playerRef = sender.GetPlayer();

        playerRef.Name             = playerName;
        playerRef.RoleListVerified = true;

        GameInfo.AddPlayerAndAssignId(playerRef);

        ServerInstance.Send(5, 0u, GenRandomJoinMessage(playerName));

        if (GameInfo.Players.Count == 1)
        {
            playerRef.IsHost = true;
            sender.Send(199, true); //SetHost(UdpClient, bool)
            ServerInstance.Send(5, 0u, $"{playerRef.Name} is now the game master.");
        }

        sender.Send(200, playerRef.PlayerID, ConnectedPlayers.Select(p => p.PlayerID).ToArray(), ConnectedPlayers.Select(p => p.Name).ToArray()); // ReceivePlayerList(uint, uint[], string[]);

        foreach (string hash in ActiveRoleHashes)
        {
            sender.Send(190, hash, false);
        }

        ServerInstance.Send(1, playerRef.PlayerID, playerRef.Name); // UpdateClientInfo(uint, string)
    }
Ejemplo n.º 20
0
        public static MethodInfo GetMethodInfo <T>(Expression <Action <T> > expression)
        {
            var member = expression.Body as MethodCallExpression;

            if (member != null)
            {
                return(member.Method);
            }

            NetBase.WriteDebug("Expression provided to MethodInfoHelper.GetMethodInfo<T> is not a method!", true);
            return(null); // Will never be hit, but is done to make C# happy that it's getting a return type.
        }
Ejemplo n.º 21
0
        public bool GetConfirm(TokenItem ti)
        {
            ResetAndInfo("Key= " + string.Join(" ,", NetBase.SubArray(ti.TokenBytes, 0, 8)) + "\n" + ti.Base64Key + "\n" + ti.Description);

            var ret  = ShowDialog();
            var bret = ret == DialogResult.Yes || ret == DialogResult.OK;

            if (ChackboxChecked)
            {
                ßMainPoint.S.ToakenList.Add(ti.Base64Key, new TokenItem(ti.TokenBytes, bret, true, this._descriptionBox.Text));
            }
            return(bret);
        }
Ejemplo n.º 22
0
 /// <summary>
 /// 加入房间
 /// </summary>
 /// <param name="id"></param>
 /// <param name="net"></param>
 public void JoinClient(int id, NetBase net)
 {
     if (clients.ContainsKey(id))
     {//顶替
         Debug.LogWarning("顶替:" + net.address + "<-->" + clients[id].address);
         clients[id].End();
         clients[id] = net;
     }
     else
     {
         clients.Add(id, net);
     }
 }
Ejemplo n.º 23
0
 // 初始化网络框架
 void _Init()
 {
     if (ThreadOrAsyn)
     {
         m_Client = new NetThread();
     }
     else
     {
         m_Client = new NetAsyn();
     }
     m_Client.OnConnectedEvent    += OnConnect;
     m_Client.OnDisConnectedEvent += OnDisConnect;
     m_Client.OnErrorEvent        += OnError;
 }
Ejemplo n.º 24
0
    /// <summary>
    /// 加载进度
    /// </summary>
    /// <param name="client"></param>
    /// <param name="datas"></param>
    private void ProgressRate(NetBase client, byte[] datas, Int32 player_id)
    {
        //pkgSCProgressRateRep data = pkgSCProgressRateRep.Parser.ParseFrom(datas);

        //Main.DebugWarning("服务器返回-加载进度->" + data.Rate + "," + data.Userid);

        //if (data.Userid == Main.game.player_1.id)
        //{
        //    Main.game.player_1.state = data.Rate;
        //}
        //else if (data.Userid == Main.game.player_2.id)
        //{
        //    Main.game.player_2.state = data.Rate;
        //}
    }
Ejemplo n.º 25
0
        internal void _Apply(NetBase net)
        {
            if (net == null)
            {
                return;
            }

            net.Configuration.ResendFunction = new NetConnection.ResendFunction(_resendFunction);

            if (net.Configuration.ReceiveBufferSize != _receiveBufferSize)
            {
                net.Configuration.ReceiveBufferSize = _receiveBufferSize;

                if (net.m_socket != null)
                {
                    net.m_socket.receiveBufferSize = _receiveBufferSize;

                    // make sure we have the actual buffer size
                    net.Configuration.ReceiveBufferSize = net.m_socket.receiveBufferSize;
                }
            }

            if (net.Configuration.SendBufferSize != _sendBufferSize)
            {
                net.Configuration.SendBufferSize = _sendBufferSize;

                if (net.m_socket != null)
                {
                    net.m_socket.sendBufferSize = _sendBufferSize;

                    // make sure we have the actual buffer size
                    net.Configuration.SendBufferSize = net.m_socket.sendBufferSize;
                }
            }

            net.Configuration.MaximumTransmissionUnit = _maximumTransmissionUnit;
            // Note that Lidgren uses "frequency" but means "time".
            net.Configuration.PingFrequency = _timeBetweenPings;
            net.Configuration.TimeoutDelay  = _timeoutDelay;
            // Note that Lidgren uses the word "attempts" when it actually means "retries", i.e always one attempt + N.
            net.Configuration.HandshakeAttemptsMaxCount   = _handshakeRetriesMaxCount;
            net.Configuration.HandshakeAttemptRepeatDelay = _handshakeRetryDelay;
            net.Configuration.AddressStr = _localIP;
            net.Configuration.SocketType = _socketType;

            net.SetMessageTypeEnabled(NetMessageType.OutOfBandData, _allowInternalUnconnectedMessages);
            net.Configuration.AllowConnectionToSelf = _allowConnectionToSelf;
        }
Ejemplo n.º 26
0
    public KCPClient(NetBase _parent)
    {
        RecvBuffer_Add = new List <byte[]>();
        RecvBuffer     = new List <byte>();

        parent = _parent;

        //pkgCSHeartBeatReq heart = new pkgCSHeartBeatReq();
        //heart.Ok = 1;
        //var mem = new MemoryStream();
        //heart.WriteTo(mem);
        //mem.Position = 0;
        //byte[] datas = mem.ToArray();
        //mem.Dispose();
        //heart_data = KCPClient.GetData(Main.game.player_1.id, 0, (int)ProtocolCmd.CsheartBeatReq, datas);
    }
        public byte[] ConvertToBytes(object instance, bool includeLength)
        {
            Enum e = (Enum)instance;
            Type underlyingType = e.GetType().GetEnumUnderlyingType();

            if (!ParentModule.HasConverterOfType(underlyingType))
            {
                NetBase.WriteDebug($"Invalid element type for enum conversion! ({underlyingType})", true);
            }

            List <byte> data = new List <byte>();

            data.AddRange(ParentModule.ConvertToBytes(Convert.ChangeType(e, underlyingType), includeLength));

            return(data.ToArray());
        }
Ejemplo n.º 28
0
        private void InitNet(NetType netType, OptType optType)
        {
            switch (optType)
            {
            case OptType.sgd:
                Opt = new Sgd(_conf.LearningRate, _conf.L2RegFactor, _conf.ClipBound, _conf.DecayRate,
                              _dataset.Examples.Count);
                break;

            case OptType.adagrad:
                Opt = new AdaGrad(_conf.LearningRate, _conf.L2RegFactor, _conf.ClipBound, _conf.Eps);
                break;

            case OptType.adam:
                Opt = new Adam(l2RegFactor: _conf.L2RegFactor, clipRange: _conf.ClipBound);
                break;

            default:
                throw new ArgumentOutOfRangeException(nameof(optType), optType, null);
            }

            var eDim = _dataset.Examples[0].Feature.Length;
            var hDim = _conf.HiddenSize;
            var oDim = _conf.LabelCount;

            switch (netType)
            {
            case NetType.mlp:
                Net = new MLP(_conf, eDim, Opt);
                break;

            case NetType.mlptop:
                Net = new MLPTop(_conf, eDim, Opt);
                break;

            case NetType.mlprand:
                Net = new MLPRand(_conf, eDim, Opt);
                break;

            default:
                throw new ArgumentOutOfRangeException(nameof(netType), netType, null);
            }
        }
Ejemplo n.º 29
0
 /// <summary>
 /// 结算
 /// </summary>
 /// <param name="client"></param>
 /// <param name="datas"></param>
 private void GameOver(NetBase client, byte[] datas, Int32 player_id)
 {
     //pkgSCARoundOverRep data = pkgSCARoundOverRep.Parser.ParseFrom(datas); //ProtoBuf.Serializer.Deserialize(typeof(pkgSCARoundOverRep), stream) as pkgSCARoundOverRep;
     //Main.DebugWarning("========结算:" + data.Ok);
     //game_result = data.Ok;
     //is_over = true;
     //switch (game_result)
     //{
     //    case 1:
     //        Main.game.state = 50;//你赢了
     //        break;
     //    case 2:
     //        Main.game.state = -50;//你输了
     //        break;
     //    case 3:
     //        Main.game.state = 60;//平局
     //        break;
     //}
 }
Ejemplo n.º 30
0
    void Start()
    {
        text_Network = GameObject.Find("Text Network").GetComponent <Text>();
        text_Connect = GameObject.Find("Text Connect").transform.Find("Text").GetComponent <Text>();
        text_Recv    = GameObject.Find("Text Recv").GetComponent <Text>();
        text_Send    = GameObject.Find("Text Send").GetComponent <Text>();

        bulletPosition            = bullet.transform.localPosition;
        bullet.transform.position = new Vector3(100, 100, 100);

        Input.gyro.enabled = true;

        switch (Application.platform)
        {
        case RuntimePlatform.WindowsEditor:
            platform = "windows";
            break;

        case RuntimePlatform.WindowsPlayer:
            platform = "windows";
            break;

        case RuntimePlatform.Android:
            platform = "android";
            break;

        default:
            platform = "error";
            break;
        }

        if (platform == "windows")
        {
            cam.GetComponent <Camera>().stereoTargetEye = StereoTargetEyeMask.None;
        }
        else if (platform == "android")
        {
            netBase = netServer = new NetServer();
            netServer.Start();
        }
    }
Ejemplo n.º 31
0
 public Inserter(NetBase.Sql.InsertQuery q)
 {
     this.Query = q;
 }