Exemplo n.º 1
0
        /// <summary>
        ///     Connect to a network game (connect to the game's P2P server).
        /// </summary>
        /// <param name="p2pServerEndPoint">Pass null to delay connection and use side-channel verification</param>
        public void ConnectToGame(INetworkApplication networkApplication, string playerName, byte[] playerData,
                                  IPEndPoint p2pServerEndPoint,
                                  ulong sideChannelId, int sideChannelToken)
        {
            if (networkApplication == null)
            {
                throw new ArgumentNullException("networkApplication");
            }

            if (peerManager != null)
            {
                throw new InvalidOperationException("Already running");
            }

            LocalisedDisconnectReason = null;

            NetworkApplication = networkApplication;
            var p2pClient = new P2PClient(this, playerName, playerData, sideChannelId, sideChannelToken);

            if (p2pServerEndPoint != null)
            {
                p2pClient.ConnectImmediate(p2pServerEndPoint);
            }
            peerManager = p2pClient;
        }
Exemplo n.º 2
0
        public void BroadcastMessageAsync(IMessage message)
        {
            for (int i = 0; i < mGroupClients.Count; ++i)
            {
                IClientDetails currClientDetails = mGroupClients[i];
                IClient        currClient        = null;

                if (clientConnections.ContainsKey(currClientDetails))
                {
                    currClient = clientConnections[currClientDetails];
                }
                else
                {
                    currClient = new P2PClient(ListenPort, currClientDetails.ClientIPAddress,
                                               currClientDetails.ClientListenPort, Group);
                    currClient.Initialize();
                }

                currClient.SendMessageAsync(message);

                if (!clientConnections.ContainsKey(currClientDetails))
                {
                    clientConnections[currClientDetails] = currClient;
                }
            }
        }
Exemplo n.º 3
0
        public override void ExecuteCommand(CustomProtocolSession session, BinaryRequestInfo requestInfo)
        {
            //TODO:

            /*
             * 数据库更新消息
             *
             */
            string id = Util.Helpers.Json.ToObject <string>(Encoding.UTF8.GetString(requestInfo.Body));

            if (P2PClient.FileCache.Keys.Any(s => s == id))
            {
                P2PClient p2PHelper = P2PClient.FileCache[id];
                p2PHelper.CancelSend();

                //P2PPackage package = new P2PPackage()
                //{
                //    RoomId = p2PHelper.To,
                //    FileName = p2PHelper.FileName,
                //    MD5 = p2PHelper.MD5,
                //    MsgId = p2PHelper.MsgId,
                //    PackageCode = P2PPakcageState.cancel
                //};
                //SDKClient.Instance.OnP2PPackagePush(package);
            }
        }
Exemplo n.º 4
0
 void Start()
 {
     client                    = new P2PClient(serverURL, roomName);
     recorder                  = new AudioCapture(8000, 320);
     recorder.OnDataRead      += Recorder_OnDataRead;
     client.OnReceivedMessage += Client_OnReceivedMessage;
 }
        public UnconnectedRemotePeer(P2PClient owner, RemotePeer remotePeer, int connectionToken, bool initiateConnection)
        {
            this.owner = owner;

            this.remotePeer         = remotePeer;
            this.connectionToken    = connectionToken;
            this.initiateConnection = initiateConnection;

            Debug.Assert(!remotePeer.IsConnected); // <- our job is to wait until we get this connection


            // Timing:
            double now = NetTime.Now;

            nextTick = now + tickRate;

            // The time-out times are calculated in the design document ("P2P Network.pptx")
            // They are dependent on the current Lidgren config, some Lidgren internals, and the punch-through settings (below)
            if (initiateConnection)
            {
                timeOutAt = now + 14; // seconds to receive punch-through message from other end so we can start initiating connection
            }
            else
            {
                timeOutAt = now + 32; // seconds to receive "Connect" (as "Accept") from other end initiating connection
            }
            // Send first punch-through:
            SendNatPunchThrough();
        }
Exemplo n.º 6
0
        private void HandleUDPP2PRequest(PacketHeader header, Connection connection, P2PClient p2pClient)
        {
            var sourceClient = _clientInfoList.FirstOrDefault(clientEx => clientEx.Client.Guid == p2pClient.GUID);

            if (sourceClient == null)
            {
                return;
            }

            if (_udpTraversal.IsSource)
            {
                ServerMessageReceivedAction(string.Format("Connect to {0}({1}:{2})", sourceClient.Client.Name, p2pClient.IP, p2pClient.Port));
                _udpTraversal.Connect(LocalClientInfo.Client.Guid, IPAddress.Parse(p2pClient.IP), p2pClient.Port);
            }
            else
            {
                ServerMessageReceivedAction(string.Format("Punch to {0}({1}:{2})", sourceClient.Client.Name, p2pClient.IP, p2pClient.Port));
                if (_udpTraversal.TryPunch(IPAddress.Parse(p2pClient.IP), p2pClient.Port))
                {
                    ServerMessageReceivedAction(string.Format("Target request to {0}", sourceClient.Client.Name));
                    _udpTraversal.Request(new P2PRequest {
                        SourceGuid = LocalClientInfo.Client.Guid, TargetGuid = p2pClient.GUID
                    }, false);
                }
            }
        }
Exemplo n.º 7
0
        public void SendMessageAsync(IMessage message, IClientDetails details)
        {
            if (message == null)
            {
                //throw a null reference exception
                throw new NullReferenceException("The supplied IMessage object is null!");
            }

            if (details == null)
            {
                //throw a null reference exception
                throw new NullReferenceException("The supplied IClientDetails object is null!");
            }

            IClient currClient = null;

            if (clientConnections.ContainsKey(details))
            {
                currClient = clientConnections[details];
            }
            else
            {
                currClient = new P2PClient(ListenPort, details.ClientIPAddress, details.ClientListenPort, Group);
                currClient.Initialize();
            }

            currClient.SendMessageAsync(message);

            if (!clientConnections.ContainsKey(details))
            {
                clientConnections[details] = currClient;
            }
        }
Exemplo n.º 8
0
 /// <summary>
 /// Entry point for our programme
 ///
 /// (Business logic, code behind, models...
 /// ...whatever you kids are calling it these days)
 /// </summary>
 public Main()
 {
     server = new P2PServer(1000);
     client = new P2PClient();
     server.OnConnectionSuccessful += SetClientFromServer;
     lewCoins = new BlockChainObj(client);
     Task serverConnection = Task.Run(() => server.Start());
 }
Exemplo n.º 9
0
 public string signalingServer = "wss://nameless-scrubland-88927.herokuapp.com"; // Please use a different server, this is mine but I'll let people use it for testing
 // Use this for initialization
 void Start()
 {
     client = new P2PClient(signalingServer, roomName);
     client.OnReceivedMessage += Client_OnReceivedMessage;
     client.OnConnection      += Client_OnConnection;
     client.OnDisconnection   += Client_OnDisconnection;
     curTime = Time.time;
 }
Exemplo n.º 10
0
 /// <summary>
 /// Block Chain constructor
 /// Both creates the chain and the genesis block
 /// </summary>
 public BlockChainObj(P2PClient client)
 {
     this.client = client;
     client.OnMessageReceived += MessageReceivedFromClient;
     chain           = new List <Block>();
     transactionPool = new TransactionPool();
     chain.Add(CreateGenesisBlock());
 }
Exemplo n.º 11
0
 // Use this for initialization
 void Start()
 {
     client = new P2PClient(pubNubPublishKey, pubNubSubscribeKey);
     client.OnNewPeerConnection += GotPeer;
     Debug.Log("My local ip: " + client.GetLocalIPAddress());
     Debug.Log("My local port: " + client.localPort);
     Debug.Log("My external ip: " + client.GetExternalIp());
     Debug.Log("My external port: " + client.externalPort);
 }
Exemplo n.º 12
0
        /// <summary>
        /// Entry point for our programme
        ///
        /// (Business logic, code behind, models...
        /// ...whatever you kids are calling it these days)
        /// </summary>
        public Main()
        {
            client = new P2PClient(1043);
            miner  = new Miner(client);

            try
            {
                Task.Run(() => client.Start());
                Task.Run(() => miner.Start());
            }
            catch (Exception ex)
            {
            }
        }
Exemplo n.º 13
0
        void Start()
        {
            client                    = new P2PClient(serverURL, roomName);
            recorder                  = new AudioCapture(8000, 320);
            recorder.OnDataRead      += Recorder_OnDataRead;
            client.OnReceivedMessage += Client_OnReceivedMessage;

            random = new System.Random();
            myId   = (int)random.Next();

            byte[] bytes = BitConverter.GetBytes(myId);
            id1 = bytes[0];
            id2 = bytes[1];
            id3 = bytes[2];
            id4 = bytes[3];
        }
Exemplo n.º 14
0
        static void Main(string[] args)
        {
            var server = new P2PServer();
            var client = new P2PClient();
            var resp   = Console.ReadLine();

            if (Uri.IsWellFormedUriString(resp, UriKind.Absolute))
            {
                blockchain.AddGenesisBlock();
                client.Connect(resp);
            }
            else if (int.TryParse(resp, out var port))
            {
                server.Start(port);
            }
            Console.ReadLine();
        }
Exemplo n.º 15
0
        public P2PClientContext(string name)
        {
            m_Owner           = new GameObject("P2PClient:" + name);
            Client            = m_Owner.AddComponent <P2PClient>();
            Client.OnMessage += (peer, buf) =>
            {
                MessageReceiveCount++;
                if (m_Message.Count > 0)
                {
                    var message = Encoding.UTF8.GetString(buf);
                    m_Message.Dequeue().TrySetResult(message);
                }
            };

            Client.OnAddPeer    += (_) => AddPeerCount++;
            Client.OnRemovePeer += (_) => RemovePeerCount++;
        }
Exemplo n.º 16
0
        public void UpdateOnClient(P2PClient owner)
        {
            if (!owner.HasServer)
            {
                return; // Don't expire any messages while we're waiting on a new server.
            }
            double expireTime = NetTime.Now - clientBufferTime;

            while (disconnectedByServerTimes.Count > 0 && disconnectedByServerTimes[0] < expireTime)
            {
                disconnectedByServerTimes.RemoveAt(0);
            }

            while (timedOutTimes.Count > 0 && timedOutTimes[0] < expireTime)
            {
                timedOutTimes.RemoveAt(0);
            }
        }
Exemplo n.º 17
0
        private async Task OnConnectionReceived(StreamSocket socket)
        {
            byte[] message = await RetrieveMessage(socket);

            var newClient = new P2PClient {
                clientTcpIP = socket.Information.RemoteAddress.ToString()
            };

            if (AcceptingConnections)
            {
                if (GetGuid(newClient).ToString() == (new Guid()).ToString())
                {
                    Guid newGuid = Guid.NewGuid();
                    this.ClientMap.Add(newGuid, newClient);
                    this.OnConnectionComplete(newGuid);
                }
            }
            this.OnMessageReceived(message, GetGuid(newClient));
        }
        public void Test1()
        {
            using BusinessLogic Program1 = new BusinessLogic();
            P2PClient server1 = new P2PClient("Источник");

            Program1.InitServer(server1);
            using BusinessLogic Program2 = new BusinessLogic();
            P2PClient server2 = new P2PClient("Приёмщик");

            Program2.InitServer(server2);
            Stopwatch sw = new Stopwatch();

            Program1.OnDebugMessage += (a, b) => Console.WriteLine($"{Program1.ToString()}: [{sw.Elapsed}] {b}");
            Program2.OnDebugMessage += (a, b) => Console.WriteLine($"{Program2.ToString()}: [{sw.Elapsed}] {b}");
            sw.Start();
            ulong From1To2 = Program1.AddConnection(server2.LocalEndPoint);
            var   toSend   = new { Type = "msg", Message = new string('g', 128) + new string('я', 128) };

            Program2.OnMessageSend += Program2_OnMessageSend;
            Program1.Send(From1To2, toSend);
            bool good = false;

            while (!tokenSource.IsCancellationRequested)
            {
                Thread.Sleep(1);
            }
            sw.Stop();
            Console.WriteLine(sw.Elapsed);
            Assert.IsTrue(good);
            return;

            void Program2_OnMessageSend(BusinessLogic arg1, ulong arg2, dynamic arg3)
            {
                PackageInfo[] messages = Program2.GetAllMessages().ToArray();
                Assert.AreEqual(1, messages.Length);
                Console.WriteLine(JsonConvert.SerializeObject(toSend));
                Assert.AreEqual(JsonConvert.SerializeObject(toSend), JsonConvert.SerializeObject(messages[0].Json));
                good = true;
                tokenSource.Cancel();
            }
        }
Exemplo n.º 19
0
        public BlockchainPeer(int listenPort, int serverListenPort, string server, string group)
        {
            mListenPort       = listenPort;
            mServerListenPort = serverListenPort;
            mServer           = server;
            mGroup            = group;

            mGroupClients = new Collection <IClientDetails>();

            mListener = new P2PServer(listenPort, group);

            ((P2PServer)mListener).GroupClientsDetails     = mGroupClients;
            ((P2PServer)mListener).OnReceiveMessage       += new OnReceiveMessageEvent(OnReceivePeerMessage);
            ((P2PServer)mListener).OnRegisterClient       += new ServerRegisterEvent(OnRegisterPeer);
            ((P2PServer)mListener).OnUnRegisterClient     += new ServerUnRegisterEvent(OnUnRegisterPeer);
            ((P2PServer)mListener).OnRecieveListOfClients += new OnRecieveListOfClientsEvent(OnRecieveListPeers);

            //mListener.Initialize();
            mClient = new P2PClient(listenPort, server, serverListenPort, group);
            //mClient.Initialize();
            clientConnections = new Dictionary <IClientDetails, IClient>();
        }
Exemplo n.º 20
0
    // Use this for initialization
    void Start()
    {
        p2pClient = new P2PClient("127.0.0.1", 3005);
        p2pServer = new P2PServer(3005);

        Game.RTM = this;
        //	t=new Thread(Program.Init);
        //	t.Start();
        //StartCoroutine(PRI());
        GameObject.DontDestroyOnLoad(this.gameObject);
        //Game.PlaySound("Bell1");

        DbAccess.OpenDB("Db.db");
        IDataReader idr = DbAccess.SQL("SELECT * FROM Subx");

        if (idr.Read())
        {
            Debug.Log(idr.GetString(idr.GetOrdinal("Name")));
        }
        //IDataReader idr= DbAccess.SQL("");
        //idr.GetByte(idr.GetOrdinal());
    }
Exemplo n.º 21
0
        public void BroadcastMessageAsyncExceptAddress(string[] addressesToExclude, IMessage message)
        {
            for (int i = 0; i < mGroupClients.Count; ++i)
            {
                IClientDetails currClientDetails = mGroupClients[i];

                var skip = false;
                for (var j = 0; j < addressesToExclude.Length; j++)
                {
                    if (addressesToExclude[j] == currClientDetails.ToString())
                    {
                        skip = true;
                    }
                }
                if (skip)
                {
                    continue;       //skip if should be excluded
                }
                //set client
                IClient currClient = null;
                if (clientConnections.ContainsKey(currClientDetails))
                {
                    currClient = clientConnections[currClientDetails];
                }
                else
                {
                    currClient = new P2PClient(ListenPort, currClientDetails.ClientIPAddress, currClientDetails.ClientListenPort, Group);
                    currClient.Initialize();
                }
                //send message
                currClient.SendMessageAsync(message);

                //add to clientConnections if not there already
                if (!clientConnections.ContainsKey(currClientDetails))
                {
                    clientConnections[currClientDetails] = currClient;
                }
            }
        }
 public P2PPeer(string localIp, string externalIp, int localPort, int externalPort, P2PClient client, bool isOnLan)
 {
     this.localIp      = localIp;
     this.externalIp   = externalIp;
     this.localPort    = localPort;
     this.externalPort = externalPort;
     this.client       = client;
     this.isOnLan      = isOnLan;
     if (isOnLan)
     {
         IPEndPoint endPointLocal = new IPEndPoint(IPAddress.Parse(localIp), localPort);
         Thread     localListener = new Thread(() => ReceiveMessage(endPointLocal));
         localListener.IsBackground = true;
         localListener.Start();
     }
     else
     {
         IPEndPoint endPoint         = new IPEndPoint(IPAddress.Parse(externalIp), externalPort);
         Thread     externalListener = new Thread(() => ReceiveMessage(endPoint));
         externalListener.IsBackground = true;
         externalListener.Start();
     }
 }
        private void button_login_Click(object sender, RoutedEventArgs e)
        {
            TcpClient tcpClient;
            IPAddress ServerIP;
            string    msg = string.Empty;

            try {
                string[] ip = textBox_ip.Text.Split(':');
                tcpClient = new TcpClient();
                ServerIP  = IPAddress.Parse(ip[0]);
                tcpClient.Connect(ServerIP, int.Parse(ip[1]));                 //建立与服务器的连接

                NetworkStream networkStream = tcpClient.GetStream();
                if (networkStream.CanWrite)
                {
                    IMClassLibrary.LoginDataPackage loginDataPackage = new IMClassLibrary.LoginDataPackage("127.0.0.1:" + MyPort.ToString(), "Server_Login", textBox_id.Text, sha256(passwordBox.Password)); //初始化登录数据包
                    Byte[] sendBytes = loginDataPackage.DataPackageToBytes();                                                                                                                                //登录数据包转化为字节数组
                    networkStream.Write(sendBytes, 0, sendBytes.Length);
                }

                msg = ListenThreadMethod();
            }
            catch {
                MessageBox.Show("与服务器连接失败!");
            }
            if (msg == "登录成功")
            {
                P2PClient client = new P2PClient(textBox_id.Text, tcpListener, MyPort, textBox_ip.Text.Split(':')[1], passwordBox_Copy.Password);                 //传入用户名&登录端口
                client.Show();
                Close();
            }
            else
            {
                MessageBox.Show("登录失败!");
            }
        }
Exemplo n.º 24
0
	// Use this for initialization
	void Start () 
	{
	

		p2pClient=new P2PClient("127.0.0.1",3005);
		p2pServer=new P2PServer(3005);

		Game.RTM=this;
	//	t=new Thread(Program.Init);
	//	t.Start();
		//StartCoroutine(PRI());
		GameObject.DontDestroyOnLoad(this.gameObject);
		//Game.PlaySound("Bell1");

		DbAccess.OpenDB("Db.db");
		IDataReader idr= DbAccess.SQL("SELECT * FROM Subx");

		if(idr.Read())
		{
			Debug.Log(idr.GetString(idr.GetOrdinal("Name")));
		}
		//IDataReader idr= DbAccess.SQL("");
		//idr.GetByte(idr.GetOrdinal());
	}
Exemplo n.º 25
0
        public override void ExecuteCommand(CustomProtocolSession session, BinaryRequestInfo requestInfo)
        {
            //TODO:

            /*
             * 生成文件
             * 生成消息记录
             */
            var obj = Util.Helpers.Json.ToObject <FileHead>(Encoding.UTF8.GetString(requestInfo.Body));

            if (P2PClient.FileCache.Keys.Any(s => s == obj.MsgId))
            {
                P2PClient p2PHelper = P2PClient.FileCache[obj.MsgId];
                p2PHelper.SendBody(session);
            }

            // msg.roomType = 0;


            //msg.msgType = nameof(SDKProperty.MessageType.onlinefile);


            //msg.fileName = obj.FileName;
            //msg.fileSize = package.data.body.fileSize;
            //msg.content = "[文件]";

            //try
            //{
            //    await SDKProperty.SQLiteConn.InsertAsync(msg);
            //}
            //catch (Exception)
            //{
            //}

            //}
        }
Exemplo n.º 26
0
 public void TestServer(Int32 _port)
 {
     P2PClient.Connect($"ws://127.0.0.1:{_port}/DCL_CORE");
 }
Exemplo n.º 27
0
        public void OnHandleClientData(IAsyncResult asyncResult)
        {
            try
            {
                TxRxPacket dataStatus = (TxRxPacket)asyncResult.AsyncState;


                dataStatus.mCurrentSocket.EndReceive(asyncResult);
                dataStatus.StoreCurrentData();


                IMessage rxMessage = mMessageParser.ParseMessage(dataStatus.mStoredBuffer);

                if (rxMessage == null)
                {
                    //receive the rest of the message
                    dataStatus.mCurrentSocket.BeginReceive(dataStatus.mDataBuffer, 0, dataStatus.mDataBuffer.Length,
                                                           SocketFlags.None, new AsyncCallback(OnHandleClientData), dataStatus);
                    return;
                }
                //handle the message (which can either be register or unregister)
                //send response message if needed
                switch (rxMessage.Type)
                {
                case ((int)MessageType.ResgisteredClientsListMessage):
                {
                    Socket workerSocket = dataStatus.mCurrentSocket;
                    //respond with the current group in the message

                    RegisteredClientsListMessage rxClientList = (RegisteredClientsListMessage)rxMessage;
                    if (rxClientList.Clients != null)
                    {
                        for (int i = 0; i < rxClientList.Clients.Count; ++i)
                        {
                            groupClientsDetails.Add(rxClientList.Clients[i]);
                            //register on each of them
                            IClient client = new P2PClient(mListenPort, rxClientList.Clients[i].ClientIPAddress,
                                                           rxClientList.Clients[i].ClientListenPort, group);
                            client.Initialize();
                            client = null;
                        }

                        if (mOnRecieveListOfClients != null && group == ((RegisteredClientsListMessage)rxMessage).Group)
                        {
                            mOnRecieveListOfClients.Invoke(this, new ReceiveListOfClientsEventArgs(((RegisteredClientsListMessage)rxMessage).Clients));
                        }
                    }

                    break;
                }

                case ((int)MessageType.RegisterMessage):
                {
                    if (!(groupClientsDetails.IndexOf(((RegisterMessage)rxMessage).Client) >= 0))
                    {
                        groupClientsDetails.Add(((RegisterMessage)rxMessage).Client);

                        if (mOnRegisterClient != null && group == ((RegisterMessage)rxMessage).Group)
                        {
                            mOnRegisterClient.Invoke(this, new ServerRegisterEventArgs(((RegisterMessage)rxMessage).Client));
                        }
                        if (mOnReceiveMessage != null)
                        {
                            mOnReceiveMessage.Invoke(this, new ReceiveMessageEventArgs(rxMessage));
                        }
                    }

                    break;
                }

                case ((int)MessageType.UnregisterMessage):
                {
                    if ((groupClientsDetails.IndexOf(((UnregisterMessage)rxMessage).Client) >= 0))
                    {
                        groupClientsDetails.Remove(((UnregisterMessage)rxMessage).Client);

                        if (mOnUnRegisterClient != null && group == ((UnregisterMessage)rxMessage).Group)
                        {
                            mOnUnRegisterClient.Invoke(this,
                                                       new ServerRegisterEventArgs(((UnregisterMessage)rxMessage).Client));
                        }
                    }

                    break;
                }

                case ((int)MessageType.CommandMessage):
                {
                    if (mOnReceiveMessage != null)
                    {
                        mOnReceiveMessage.Invoke(this, new ReceiveMessageEventArgs(rxMessage));
                    }
                    break;
                }

                default:
                {
                    if (rxMessage.Type != ((int)MessageType.EmptyMessage))
                    {
                        if (mOnReceiveMessage != null)
                        {
                            mOnReceiveMessage.Invoke(this,
                                                     new ReceiveMessageEventArgs(rxMessage));
                        }
                    }

                    break;
                }
                }
            }
            catch (ObjectDisposedException ex)
            {
                System.Diagnostics.Debug.WriteLine("Socket has been closed : " + ex.Message);
            }
            catch (SocketException ex)
            {
                if (ex.ErrorCode == 10054) // Error code for Connection reset by peer
                {
                    System.Diagnostics.Debug.WriteLine("Connection reset by peer : " + ex.Message);
                }
                else
                {
                    System.Diagnostics.Debug.WriteLine(ex.Message);
                }
            }
        }
Exemplo n.º 28
0
 /// <summary>
 /// Block Chain constructor
 /// Both creates the chain and the genesis block
 /// </summary>
 public Miner(P2PClient client)
 {
     this.client = client;
     client.OnMessageReceived += MessageReceivedFromClient;
     transactionPool           = new TransactionPool();
 }
Exemplo n.º 29
0
        /// <summary>
        /// 管道数据读取回调方法
        /// </summary>
        /// <param name="ar"></param>
        protected void ReadCallBack(string strData, PipeStream pipe)
        {
            string[] strSplit = strData.Split(' ').Where(t => !string.IsNullOrWhiteSpace(t)).ToArray();

            if (strSplit[0] == "ls")
            {
                string msg = "当前监听端口:";
                appCenter.Config.PortMapList.ForEach(t => { msg += t.LocalPort + " "; });
                ReplayCmdMsg(pipe, msg);
            }
            else if (strSplit[0] == "v")
            {
                ReplayCmdMsg(pipe, $"当前版本 { EasyInject.Get<AppCenter>().SoftVerSion}");
            }
            else if (strSplit[0] == "use")
            {
                IConfig configManager = EasyInject.Get <IConfig>();
                EasyOp.Do(() =>
                {
                    PortMapItem obj = configManager.ParseToObject("[PortMapItem]", strSplit[1]) as PortMapItem;
                    if (obj != null)
                    {
                        //设置配置文件更新时间,避免出发重加载配置文件逻辑
                        appCenter.LastUpdateConfig = DateTime.Now;
                        //添加/修改指定项到配置文件
                        configManager.SaveItem(obj);
                        P2PClient client = EasyInject.Get <P2PClient>();
                        //监听/修改端口映射
                        if (client.UsePortMapItem(obj))
                        {
                            appCenter.Config.PortMapList.Add(obj);
                            ReplayCmdMsg(pipe, "添加/修改端口映射成功!");
                            LogUtils.Info($"管道命令:添加/修改端口映射 {obj.LocalPort}->{obj.RemoteAddress}:{obj.RemotePort}");
                        }
                        else
                        {
                            ReplayCmdMsg(pipe, "添加/修改端口映射失败,请参考wiki中的端口映射配置项!");
                        }
                    }
                    else
                    {
                        ReplayCmdMsg(pipe, "添加/修改端口映射失败,请参考wiki中的端口映射配置项!");
                    }
                }, e =>
                {
                    ReplayCmdMsg(pipe, $"添加/修改端口映射异常:{e}");
                });
            }
            else if (strSplit[0] == "del")
            {
                int localPort;
                if (int.TryParse(strSplit[1], out localPort))
                {
                    EasyOp.Do(() =>
                    {
                        //设置配置文件更新时间,避免出发重加载配置文件逻辑
                        appCenter.LastUpdateConfig = DateTime.Now;
                        P2PClient client           = EasyInject.Get <P2PClient>();
                        //停止监听端口
                        client.UnUsePortMapItem(localPort);
                        IConfig configManager = EasyInject.Get <IConfig>();
                        //移除配置文件中指定项
                        configManager.RemoveItem(new PortMapItem()
                        {
                            LocalPort = localPort
                        });
                        ReplayCmdMsg(pipe, "移除端口映射成功!");
                        LogUtils.Info($"管道命令:移除端口映射 {localPort}");
                    }, e =>
                    {
                        ReplayCmdMsg(pipe, $"移除端口映射异常:{e}");
                    });
                }
                else
                {
                    ReplayCmdMsg(pipe, "移除端口映射失败!");
                }
            }
            else if (strSplit[0] == "log")
            {
                if (strSplit.Length == 2 && strSplit[1] == "-s")
                {
                    LogItem pipeSt = logItems.FirstOrDefault(t => t.item == pipe);
                    logItems.Remove(pipeSt);
                    ReplayCmdMsg(pipe, "停止记录日志");
                }
                else
                {
                    LogLevel level = appCenter.Config.LogLevel;
                    if (strSplit.Length == 2)
                    {
                        switch (strSplit[1].ToLower())
                        {
                        case "debug": level = LogLevel.Debug; break;

                        case "error": level = LogLevel.Error; break;

                        case "info": level = LogLevel.Info; break;

                        case "none": level = LogLevel.None; break;

                        case "warning": level = LogLevel.Warning; break;

                        case "trace": level = LogLevel.Trace; break;
                        }
                    }
                    if (!logItems.Any(t => t.item == pipe))
                    {
                        LogItem item = new LogItem();
                        item.item  = pipe;
                        item.level = level;
                        logItems.Add(item);
                        ReplayCmdMsg(pipe, $"开始记录日志,级别:{level}");
                    }
                    else
                    {
                        LogItem pipeSt = logItems.FirstOrDefault(t => t.item == pipe);
                        pipeSt.level = level;
                        ReplayCmdMsg(pipe, $"设置日志级别:{level}");
                    }
                }
            }
            else if (strSplit[0] == "h")
            {
                string msg = "";
                using (MemoryStream ms = new MemoryStream())
                {
                    StreamWriter writer = new StreamWriter(ms);
                    writer.WriteLine("1.开始日志打印: log [Debug/Info/Warning/Trace]");
                    writer.WriteLine("2.结束日志打印: log -s");
                    writer.WriteLine("3.获取监听端口: ls");
                    writer.WriteLine("4.获取当前版本: v");
                    writer.WriteLine("5.添加/修改端口映射: use 映射配置  (例:\"use 12345->[ClientA]:3389\")");
                    writer.WriteLine("6.删除指定端口映射: del 端口号 (例:\"del 3388\")");
                    writer.Close();
                    msg = Encoding.UTF8.GetString(ms.ToArray());
                }
                ReplayCmdMsg(pipe, msg);
            }
            else
            {
                ReplayCmdMsg(pipe, "暂不支持此命令,输入\"h\"查看帮助");
            }
        }
Exemplo n.º 30
0
        static void TestBlockChain(string[] args)
        {
            if (args.Length >= 1)
            {
                Port = int.Parse(args[0]);
            }
            if (args.Length >= 2)
            {
                name = args[1];
            }

            if (Port > 0)
            {
                Server = new P2PServer(ipAddress, Port, PhillyCoin);
                Server.Start();
                Console.WriteLine($"P2P server is running on {ipAddress}:{Port}......");
            }
            if (name != "Unkown")
            {
                Console.WriteLine($"Current user is {name}");
            }

            Console.WriteLine("=========================");
            Console.WriteLine("1. Connect to a server");
            Console.WriteLine("2. Add a transaction");
            Console.WriteLine("3. Display Blockchain");
            Console.WriteLine("4. Exit");
            Console.WriteLine("=========================");

            int selection = 0;

            while (selection != 4)
            {
                switch (selection)
                {
                case 1:
                    Console.WriteLine("Please enter the server URL");
                    string serverURL = Console.ReadLine();
                    Client = new P2PClient(PhillyCoin);
                    Client.Connect($"{serverURL}/Blockchain");
                    break;

                case 2:
                    Console.WriteLine("Please enter the receiver name");
                    string receiverName = Console.ReadLine();
                    Console.WriteLine("Please enter the amount");
                    string amount = Console.ReadLine();
                    PhillyCoin.CreateTransaction(new Transaction(name, receiverName, int.Parse(amount)));
                    PhillyCoin.ProcessPendingTransactions(name);
                    Client = new P2PClient(PhillyCoin);
                    Client.Broadcast(JsonConvert.SerializeObject(PhillyCoin));
                    break;

                case 3:
                    Console.WriteLine("BlockChain");
                    Console.WriteLine(JsonConvert.SerializeObject(PhillyCoin, Formatting.Indented));
                    break;
                }

                Console.WriteLine("Please select an action");
                string action = Console.ReadLine();
                selection = int.Parse(action);
            }

            Client.Close();
        }
Exemplo n.º 31
0
        static void Main(string[] args)
        {
            P2PClient client = new P2PClient()
            {
                Signer = new ECDSASignatureProvider()
            };

            #region Connection.

            client.Connect("ws://" + Dns.GetHostName() + ":8900/simplecoin");

            Thread.Sleep(4000);

            #endregion

            #region Block sending.

            Block block = new Block(
                new byte[] { randomByte(), randomByte(), randomByte() },
                new byte[] { randomByte(), randomByte(), randomByte() },
                new Transaction[]
            {
                new Transaction
                (
                    new byte[] { randomByte(), randomByte(), randomByte() },
                    new byte[] { randomByte(), randomByte(), randomByte() },
                    random.Next(1, 100),
                    new TransactionHashFactory()
                ),
                new Transaction
                (
                    new byte[] { randomByte(), randomByte(), randomByte() },
                    new byte[] { randomByte(), randomByte(), randomByte() },
                    random.Next(1, 100),
                    new TransactionHashFactory()
                )
            },
                new KeccakFactory(512, 64)
                );

            client.SendBlock(block);

            Thread.Sleep(1000);

            #endregion

            #region Transaction sending.

            Transaction transaction = new Transaction
                                      (
                new byte[] { randomByte(), randomByte(), randomByte() },
                new byte[] { randomByte(), randomByte(), randomByte() },
                random.Next(1, 100),
                new TransactionHashFactory()
                                      );

            client.SendTransaction(transaction);

            Thread.Sleep(1000);

            #endregion

            client.Disconnect();

            client.Connect("ws://" + Dns.GetHostName() + ":8900/simplecoin");

            Thread.Sleep(1000);

            client.SendTransaction(transaction);
        }
 private async Task OnConnectionReceived(StreamSocket socket)
 {
     byte[] message = await RetrieveMessage(socket);
     var newClient = new P2PClient { clientTcpIP = socket.Information.RemoteAddress.ToString() };
     if (AcceptingConnections)
     { 
         if (GetGuid(newClient).ToString() == (new Guid()).ToString())
         {
             Guid newGuid = Guid.NewGuid();
             this.ClientMap.Add(newGuid, newClient);
             this.OnConnectionComplete(newGuid);
         }
     }
     this.OnMessageReceived(message, GetGuid(newClient));
 }
 private Guid GetGuid(P2PClient client)
 {
     return this.ClientMap.FirstOrDefault(
         kvp => kvp.Value.clientTcpIP == client.clientTcpIP).Key;
 }