Example #1
0
 internal Client(NetStream stream, String user, Int32 sec, System.Net.IPEndPoint ip)
 {
     Stream = stream;
     Username = user;
     SecurityLevel = sec;
     Ip = ip;
 }
Example #2
0
 private void connect_Click(object sender, EventArgs e)
 {
     byte[] buff = new byte[255];
     System.Net.IPEndPoint IP = new System.Net.IPEndPoint(System.Net.IPAddress.Parse(txtIP.Text),Convert.ToInt32(txtPort.Text));
     telnet.Connect(IP,txtsysop.Text,txtlock.Text);
     timRecv.Enabled = true;
 }
Example #3
0
        public SDL()
        {
            Initialise();
            
            #region Connect To Server
            System.Net.IPEndPoint tempIpAddress = new System.Net.IPEndPoint(System.Net.IPAddress.Parse("127.0.0.1"), 8001);
            Stromohab_MCE_Connection.TCPProcessor.ConnectToServer(tempIpAddress);
            
            Stromohab_MCE_Connection.SendMCECommand.StartCameras();
            Stromohab_MCE_Connection.TCPProcessor.JointListReceivedEvent += new Stromohab_MCE_Connection.TCPProcessor.JointListReceivedHandler(TCPProcessor_JointListReceivedEvent);
            Stromohab_MCE_Connection.TCPProcessor.TrackableListReceivedEvent += new Stromohab_MCE_Connection.TCPProcessor.TrackableListReceivedHandler(TCPProcessor_TrackableListReceivedEvent);
            #endregion Connect To Server
            
            
            #region Remoting
            //Register for events and pre-set all trackables to draw

            
            ChannelServices.RegisterChannel(new TcpChannel(8008),false);
            RemotingConfiguration.RegisterWellKnownServiceType(typeof(OpenGLViewer.OpenGLViewerRemoteControl), "Remote", WellKnownObjectMode.Singleton);

            

            #endregion Remoting
            
        }
Example #4
0
        static void Send(List<GPSDataEntity> data ,string datatype)
        {
            MemoryStream ms = new MemoryStream();//创建内存流对象
            new BinaryFormatter().Serialize(ms, data);//将序列化信息放入内存流
            byte[] bytes = ms.ToArray();

            string businessIP = ConfigHelper.GetConfig("businessServerIP");
            int businessPort = int.Parse(ConfigHelper.GetConfig("businessserverport"));
            string protocolType = ConfigHelper.GetConfig("protocolType");
            if (protocolType == "udp")
            {
                System.Net.IPEndPoint business = new System.Net.IPEndPoint(System.Net.IPAddress.Parse(businessIP), businessPort);
                udp.SendTo(business, bytes);
                System.Console.WriteLine("udp send " + dataQty + " " + datatype + " " + bytes.Length + " bytes to business ok");
            }
            else if (protocolType == "tcp")
            {
                System.Net.Sockets.NetworkStream ns = tcp.GetStream();
                ns.Write(bytes, 0, bytes.Length);
                ns.Flush();
                //ns.Close();
                System.Console.WriteLine("tcp send " + dataQty + " " + datatype + " " + bytes.Length + " bytes to business ok");
            }

            System.Threading.Thread.Sleep(sendinterval);
        }
Example #5
0
        static void RunServer()
        {
            System.Net.IPEndPoint anyIP = new System.Net.IPEndPoint(System.Net.IPAddress.Any, 0);
            System.Net.Sockets.UdpClient udpListener = new System.Net.Sockets.UdpClient(514);
            byte[] bReceive; string sReceive; string sourceIP;

            /* Main Loop */
            /* Listen for incoming data on udp port 514 (default for SysLog events) */
            while (true)
            {
                try
                {
                    bReceive = udpListener.Receive(ref anyIP);
                    
                    // Convert incoming data from bytes to ASCII
                    sReceive = System.Text.Encoding.ASCII.GetString(bReceive);
                    
                    // Get the IP of the device sending the syslog
                    sourceIP = anyIP.Address.ToString();

                    // Start a new thread to handle received syslog event
                    new System.Threading.Thread(new logHandler(sourceIP, sReceive).handleLog).Start();
                    
                }
                catch (System.Exception ex) 
                { 
                    System.Console.WriteLine(ex.ToString()); 
                }
            } // Whend

        } // End Sub Main 
Example #6
0
        static void Main(string[] args)
        {
            Client c = new Client();

            try
            {
                //create a new client socket ...
                c.m_socClient = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                String szIPSelected = "127.0.0.1";
                String szPort = "8221";
                int alPort = System.Convert.ToInt16(szPort, 10);

                System.Net.IPAddress remoteIPAddress = System.Net.IPAddress.Parse(szIPSelected);
                System.Net.IPEndPoint remoteEndPoint = new System.Net.IPEndPoint(remoteIPAddress, alPort);
                c.m_socClient.Connect(remoteEndPoint);
                String szData = "Hello There";
                Console.WriteLine("Sending message");
                byte[] byData = System.Text.Encoding.UTF8.GetBytes(szData);
                c.m_socClient.Send(byData);
                Console.WriteLine("Sent");
                c.m_socClient.Close();
            }
            catch (SocketException se)
            {
                Console.WriteLine(se.Message);
            }
        }
Example #7
0
        /// <summary>
        /// 
        /// </summary>
        /// <param name="endPointIP">Sender IPAddress</param>
        /// <param name="endPointPort">Sender Port</param>
        /// <param name="messageType">Message Type:
        /// ISO8583.
        /// XML.
        /// EXCEL.</param>
        public DotNetPosMain(string endPointIP, int endPointPort, MessageType messageType)
        {
            _msgType = messageType;

            destinationEndPoint =
               new System.Net.IPEndPoint(System.Net.IPAddress.Parse(endPointIP), endPointPort);
        }
Example #8
0
        public static void WriteLog(string sApplicationName, string sMsg)
        {
            lock (typeof(CarverLabUtility.Logger))
            {
                string FILENAME = @"c:\" + sApplicationName + ".log";
                System.IO.StreamWriter fsw;
                string sOut = "[" + System.DateTime.Now.ToString("G") + "] " + sMsg;

                if (System.IO.File.Exists(FILENAME))
                {
                    fsw = System.IO.File.AppendText(FILENAME);
                }
                else
                {
                    fsw = System.IO.File.CreateText(FILENAME);
                }
                fsw.WriteLine(sOut);
                fsw.Close();
                System.Diagnostics.Trace.WriteLine(sMsg);

                System.Net.IPEndPoint ipep = new System.Net.IPEndPoint(System.Net.IPAddress.Loopback,61288);
                System.Net.Sockets.UdpClient uc = new System.Net.Sockets.UdpClient(System.Net.Sockets.AddressFamily.InterNetwork);
                uc.Send(System.Text.Encoding.ASCII.GetBytes(sOut),sOut.Length,ipep);
            }
        }
 public void ConnectToServer()
 {
     soc = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
     //ipAdd = System.Net.IPAddress.Parse("10.1.70.50");
     ipAdd = System.Net.IPAddress.Parse("192.168.0.18");
     remoteEP = new System.Net.IPEndPoint(ipAdd, 1337);
     soc.Connect(remoteEP);
 }
Example #10
0
 private async void MainForm_Load(object sender, EventArgs e)
 {
     var endPoint = new System.Net.IPEndPoint(System.Net.IPAddress.Loopback, 1380);
     var state = await RemoteServer.Instance.Connect(endPoint);
     var version = state ? await RemoteServer.Instance.GetVersion() : null;
     this.Text = state ? ("服务版本:" + version) : "连接服务器失败 ..";
     this.btn_Login.Enabled = this.btn_Pass.Enabled = state;
 }
Example #11
0
        public Socket(String host, int port)
        {
            System.Net.IPHostEntry hostEntry = System.Net.Dns.GetHostEntry (host);
            System.Net.IPAddress serverIP =  hostEntry.AddressList [0];
            System.Net.IPEndPoint serverEP = new System.Net.IPEndPoint(serverIP,port);

            this.delegateInstance = new System.Net.Sockets.Socket(System.Net.Sockets.AddressFamily.InterNetwork, System.Net.Sockets.SocketType.Stream, System.Net.Sockets.ProtocolType.Tcp);
        }
 /// <summary>
 /// will want to catch exception that occur in here and let someone know
 /// </summary>
 /// <param name="settings"></param>
 public void SetSettings(ChiefMarleyControllerSettings settings)
 {
     // set addressing
     System.Net.IPAddress ipAddr;
     ipAddr = System.Net.IPAddress.Parse(settings.IpAddress);
     System.Net.IPEndPoint endPoint = new System.Net.IPEndPoint(ipAddr, settings.Port);
     addressing1.SetConnection(endPoint);
 }
Example #13
0
        private void bw_DoWork(object sender, DoWorkEventArgs e)
        {
            try
            {
                byte[] buf;
                if (random == true)
                {
                    buf = System.Text.Encoding.ASCII.GetBytes(String.Format(Data, new Functions().RandomString()));
                }
                else
                {
                    buf = System.Text.Encoding.ASCII.GetBytes(Data);
                }

                var RHost = new System.Net.IPEndPoint(System.Net.IPAddress.Parse(IP), Port);
                while (IsFlooding)
                {
                    Socket socket = null;
                    if (Protocol == 1)
                    {
                        socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                        socket.NoDelay = true;

                        try { socket.Connect(RHost); }
                        catch { continue; }

                        socket.Blocking = Resp;
                        try
                        {
                            while (IsFlooding)
                            {
                                FloodCount++;
                                socket.Send(buf);
                                if (Delay >= 0) System.Threading.Thread.Sleep(Delay+1);
                            }
                        }
                        catch { }
                    }
                    if (Protocol == 2)
                    {
                        socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
                        socket.Blocking = Resp;
                        try
                        {
                            while (IsFlooding)
                            {
                                FloodCount++;
                                socket.SendTo(buf, SocketFlags.None, RHost);
                                if (Delay >= 0) System.Threading.Thread.Sleep(Delay+1);
                            }
                        }
                        catch { }
                    }
                }
            }
            catch { }
        }
Example #14
0
 public void ConnectEvent()
 {
     Socket.ConnectEvent ev = EventFactory.CreateFromXml(TestEventXml.E084_Connect) as Socket.ConnectEvent;
     Assert.That(ev, Is.Not.Null);
     Assert.That(ev.Socket, Is.EqualTo(0x8ac));
     System.Net.IPEndPoint expectedEndpoint = new System.Net.IPEndPoint(System.Net.IPAddress.Parse("65.54.239.20"), 1863);
     Assert.That(ev.RemoteEndPoint, Is.EqualTo(expectedEndpoint));
     Assert.That(ev.Result, Is.EqualTo(Socket.ConnectResult.WouldBlock));
 }
 /// <summary>
 /// to array
 /// </summary>
 /// <returns></returns>
 public System.Net.IPEndPoint[] ToArray()
 {
     var endpoints = new System.Net.IPEndPoint[base.Count];
     for (int i = 0, l = this.Count; i < l; i++)
     {
         var child = this[i];
         endpoints[i] = new System.Net.IPEndPoint(System.Net.IPAddress.Parse(child.Host), child.Port);
     }
     return endpoints;
 }
Example #16
0
 public void Deactivate()
 {
     if (m_Running)
     {
         m_Running = false;
         m_Reader.Close();
         m_RemoteNode = null;
         m_Reader = null;
     }
 }
Example #17
0
 public SocketClientWithAck(ConnectArgs args, SocketCommandArgs socketArgs)
 {
     _args = args;
     _socketArgs = socketArgs;
     _endpoint = SocketUtility.GetFirstIpEndPoint(_args.Server, _args.Port);
     _clients = new List<IConnection<Context<byte[]>, byte[]>>();
     _connections = GetNext().GetEnumerator();
     _payload = GetChars(_socketArgs.Size);
     _monitor = new ConnectionRateMonitor();
 }
Example #18
0
 static void Main(string[] args)
 {
     System.Net.IPEndPoint ep = new System.Net.IPEndPoint(System.Net.IPAddress.Any, 4004);
     SyslogDaemon daemon = new SyslogDaemon(ep, Encoding.UTF8);
     IServerStatus istatus = (IServerStatus)daemon;
     ServerStatusLogger logger = new ServerStatusLogger(ref istatus, Encoding.UTF8);
     logger.LogEntryAdded += new EventHandler<Just.EventArguments.StringEventArgs>(logger_LogEntryAdded);
     daemon.StartReceiving();
     Console.Read();
 }
Example #19
0
 //建议Socket连接
 private void Connect()
 {
     //连接服务器主机
     this.socket = new Socket (AddressFamily.InterNetwork, SocketType.Stream, ProtocolType .Tcp );
     System.Net.IPAddress IP = System.Net .IPAddress .Parse (this.host);
     System.Net.IPEndPoint ipe = new System.Net.IPEndPoint(IP, port);
     this.socket.SendTimeout = timeout;
     this.socket.ReceiveTimeout = timeout;
     this.socket.Connect(ipe);
 }
Example #20
0
        static void ListenThreadProc()
        {

            bool keepgoing = true;
            while (keepgoing)
            {
                try
                {
                    if (lsock != null)
                    {
                        lsock.Close();
                    }

                    lsock = new System.Net.Sockets.Socket(System.Net.Sockets.AddressFamily.InterNetwork,
                        System.Net.Sockets.SocketType.Stream, System.Net.Sockets.ProtocolType.Tcp);
                    System.Net.IPEndPoint ipep = new System.Net.IPEndPoint(System.Net.IPAddress.Any, 55905);
                    for (int i = 0; ; i++)
                    {
                        try
                        {
                            lsock.Bind(ipep);
                            break;
                        }
                        catch
                        {
                            if (i >= 5)
                            {
                                throw;
                            }
                            System.Threading.Thread.Sleep(1000 * 4);
                            continue;
                        }
                    }

                    lsock.Listen(30);

                    for (; ; )
                    {
                        System.Net.Sockets.Socket dllclientSock = lsock.Accept();
                        DfsProtocolClientHandler ch = new DfsProtocolClientHandler();
                        System.Threading.Thread cthd = new System.Threading.Thread(new System.Threading.ParameterizedThreadStart(ch.ClientThreadProc));
                        cthd.IsBackground = true;
                        cthd.Start(dllclientSock);
                    }
                }
                catch (System.Threading.ThreadAbortException e)
                {
                    keepgoing = false;
                }
                catch (Exception e)
                {
                    XLog.errorlog("DfsProtocol.ListenThreadProc exception: " + e.ToString());
                }
            }
        }
Example #21
0
        private async void MainForm_Load(object sender, EventArgs e)
        {
            RemoteServer.Instance.Serializer = new FastJsonSerializer();

            var endPoint = new System.Net.IPEndPoint(System.Net.IPAddress.Loopback, 1350);
            var state = await RemoteServer.Instance.Connect(endPoint);
            var version = state ? await RemoteServer.Instance.GetVersion() : "未知";

            this.Text = "连接" + (state ? "成功" : "失败") + " 服务版本:" + version;
            this.btn_Login.Enabled = this.btn_Pass.Enabled = state;
        }
Example #22
0
        public SensorBase(int id, string sensorname, System.Net.IPEndPoint endpoint )
        {
            this.ComType = COMTYPE.TCP;
               this.SensorName = sensorname;
               this.endpoint = endpoint;

               new System.Threading.Thread(TCPConnectTask).Start();
               ID = id;
               OneMinTmr.Interval = 1000 * 60;
               OneMinTmr.Elapsed += new System.Timers.ElapsedEventHandler(OneMinTmr_Elapsed);
               OneMinTmr.Start();
        }
Example #23
0
        public static void Broadcast()
        {
            byte[] bytes = new byte[NAEHandler.BroadcastMessage.Length + 2];
            Encoding.ASCII.GetBytes(NAEHandler.BroadcastMessage, 0, NAEHandler.BroadcastMessage.Length, bytes, 0);
            BitConverter.GetBytes((ushort)0).CopyTo(bytes, NAEHandler.BroadcastMessage.Length);

            System.Net.Sockets.UdpClient client = new System.Net.Sockets.UdpClient();
            System.Net.IPEndPoint groupEP = new System.Net.IPEndPoint(System.Net.IPAddress.Broadcast, NAEHandler.BroadcastPort);

            client.Send(bytes, bytes.Length, groupEP);
            client.Close();
        }
Example #24
0
 public static void getEndPoint(Packet p, out System.Net.IPEndPoint src, out System.Net.IPEndPoint dest)
 {
     if (p.PayloadPacket is IpPacket)
         if (p.PayloadPacket.PayloadPacket is TcpPacket)
         {
             src = new System.Net.IPEndPoint((p.PayloadPacket as IpPacket).SourceAddress,
                 (p.PayloadPacket.PayloadPacket as TcpPacket).SourcePort);
             dest = new System.Net.IPEndPoint((p.PayloadPacket as IpPacket).DestinationAddress,
                 (p.PayloadPacket.PayloadPacket as TcpPacket).DestinationPort);
             return;
         }
     src = null; dest = null;
 }
Example #25
0
 private void Connect(object stateInfo)
 {
     try
     {
         _clientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.IP);
         System.Net.IPAddress ipAddress = System.Net.IPAddress.Parse("192.168.1.10");
         System.Net.IPEndPoint remoteEndPoint = new System.Net.IPEndPoint(ipAddress, 9000);
         _clientSocket.Connect(remoteEndPoint);
     }
     catch (Exception e)
     {
         MessageBox.Show(e.Message);
         EnableControl(connectButton, true);
     }
 }
Example #26
0
 public IncomingMessageData(string[] _messageData, System.Net.IPEndPoint _remoteIP)
 {
     _CommandName = _messageData[0];
     if (_messageData.Length > 1)
         _UserName = _messageData[1];
     _IP = _remoteIP;
     if (_messageData.Length > 2)
     {
         List<string> blargh = new List<string>();
         for (int i = 2; i < _messageData.Length; i++)
         {
             blargh.Add(_messageData[i]);
         }
         _ExtraneousLines = blargh.ToArray();
     }
 }
Example #27
0
		private void BroadcastReadThread()
		{
			try
			{
                System.Net.IPEndPoint LocalIpEndPoint = new System.Net.IPEndPoint(System.Net.IPAddress.Any, Globals.UDP_Port);//we want to receive on all ips for our set port
                System.Net.IPEndPoint RemoteIpEndPoint = new System.Net.IPEndPoint(System.Net.IPAddress.Broadcast, 0);//ghetto port shit... tells us where it came from
                
                UdpClient udp_receive = new UdpClient();

                udp_receive.Client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true);
                udp_receive.ExclusiveAddressUse = false;

                udp_receive.Client.Bind(LocalIpEndPoint);

				byte[] buff = new byte[1024];
				NetPacket np = new NetPacket();

				while(true == true)//Globals.gamedata.running)
				{
                    //this is a blocking call... hence no need to sleep ever
                    buff = udp_receive.Receive(ref RemoteIpEndPoint);
					np.Parse(buff);

                    switch ((NetPacketType)np.Type)
					{
                        case NetPacketType.Update://standard cp/hp/mp update
							BroadCastStautsUpdate(np);
							break;
                        case NetPacketType.Script://script net send
                            ScriptNetEvent(np);
                            break;
                        case NetPacketType.ScriptBB://script net send
                            ScriptNetEventBB(np);
                            break;
                        case NetPacketType.NPCUpdate:
                            BroadCastStautsUpdateNPC(np);
                            break;
                    }
				}

                //udp_receive.Close();
			}
			catch
			{
				Globals.l2net_home.Add_Error("NetError - local broadcast read thread failed");
			}
		}
Example #28
0
        public Connection(string IPAddress)
        {
            //create a new client socket ...
            m_socClient = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            String szIPSelected = IPAddress;
            String szPort = "3000";
            int alPort = System.Convert.ToInt16(szPort, 10);

            System.Net.IPAddress remoteIPAddress = System.Net.IPAddress.Parse(szIPSelected);
            System.Net.IPEndPoint remoteEndPoint = new System.Net.IPEndPoint(remoteIPAddress, alPort);
            m_socClient.Connect(remoteEndPoint);
            //String szData = "Hello There";
            //Console.WriteLine("Sending message");
            //byte[] byData = System.Text.Encoding.UTF8.GetBytes(szData);
            //m_socClient.Send(byData);
            //Console.WriteLine("Sent");
            //m_socClient.Close();
        }
Example #29
0
        private void Connect()
        {
            try
            {
                //Creating a Client Socket
                oSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream,
                    ProtocolType.Tcp);

                System.Net.IPAddress oIPAddress = System.Net.IPAddress.Parse(sRecieverIP);
                System.Net.IPEndPoint oEndPoint = new System.Net.IPEndPoint(oIPAddress,
                    iRecieverPort);
                oSocket.Connect(oEndPoint);
            }
            catch (SocketException se)
            {
                System.Diagnostics.Debugger.Log(0, "1", se.Message);
            }
        }
Example #30
0
        protected override void Load(ContainerBuilder builder)
        {
            var ip = string.IsNullOrWhiteSpace(IpAddress)
                ? System.Net.IPAddress.Any
                : System.Net.IPAddress.Parse(IpAddress)
                ;
            var endpoint = new System.Net.IPEndPoint(ip, Port);

            // Obviously bad things will happen if multiple services
            // attempt to resolve the listener
            // but can't just be SingleInstance() as might have multiple
            // as long as *setup on different ports*
            builder.RegisterType<OpcCommandListener>()
                .WithParameter(TypedParameter.From(endpoint))
                .AsSelf()
                .AsImplementedInterfaces()
                ;
        }
Example #31
0
 public TcpListener(System.Net.IPEndPoint localEP)
 {
 }
 public IPEndPoint(string address, int port)
 {
     Address   = address;
     Port      = port;
     _EndPoint = new System.Net.IPEndPoint(IPAddress.Parse(address), port);
 }
        IReceiveFilter <SocketRequestInfo> IReceiveFilterFactory <SocketRequestInfo> .CreateFilter(SuperSocket.SocketBase.IAppServer appServer, SuperSocket.SocketBase.IAppSession appSession, System.Net.IPEndPoint remoteEndPoint)
        {
            var castedServer = (SocketServer)appServer;
            var result       = new SocketReceiveFilter(castedServer.CommandRuleProvider);

            return(result);
        }
Example #34
0
        /// <summary>
        /// The main thread of the ftp server
        /// Listen and acception clients, create handler threads for each client
        /// </summary>
        private void ThreadRun()
        {
            FtpServerMessageHandler.Message += TraceMessage;

            // listen at the port by the "FTP" endpoint setting
            System.Net.IPEndPoint ipEndPoint = RoleEnvironment.CurrentRoleInstance.InstanceEndpoints["FTP"].IPEndpoint;
            m_socketListen = SocketHelpers.CreateTcpListener(ipEndPoint);

            if (m_socketListen != null)
            {
                Trace.TraceInformation("FTP Server listened at: " + ipEndPoint);

                m_socketListen.Start();

                Trace.TraceInformation("FTP Server Started");

                bool fContinue = true;

                while (fContinue)
                {
                    TcpClient socket = null;

                    try
                    {
                        socket = m_socketListen.AcceptTcpClient();
                    }
                    catch (SocketException)
                    {
                        fContinue = false;
                    }
                    finally
                    {
                        if (socket == null)
                        {
                            fContinue = false;
                        }
                        else if (m_apConnections.Count >= m_maxClients)
                        {
                            Trace.WriteLine("Too many clients, won't handle this connection", "Warnning");
                            SendRejectMessage(socket);
                            socket.Close();
                        }
                        else
                        {
                            socket.NoDelay = false;

                            m_nId++;

                            FtpServerMessageHandler.SendMessage(m_nId, "New connection");

                            SendAcceptMessage(socket);
                            InitialiseSocketHandler(socket);
                        }
                    }
                }
            }
            else
            {
                FtpServerMessageHandler.SendMessage(0, "Error in starting FTP server");
            }
        }
 public void Listen(System.Net.IPEndPoint endPoint, System.Action <Microsoft.AspNetCore.Server.Kestrel.Core.ListenOptions> configure)
 {
 }
Example #36
0
 public S2C_HolePunchingMessage(System.Net.IPEndPoint point)
 {
     this._remotePoint = point;
 }
Example #37
0
 /// <summary>
 /// Represent an IP end point in the gateway URI format..
 /// </summary>
 /// <param name="ep">The input IP end point</param>
 /// <returns></returns>
 public static Uri ToGatewayUri(this System.Net.IPEndPoint ep)
 {
     return(new Uri(string.Format("gwy.tcp://{0}:{1}/0", ep.Address, ep.Port)));
 }
        public static async Task Test()
        {
            var systemR = AllPet.Pipeline.PipelineSystem.CreatePipelineSystemV1(new AllPet.Common.Logger());

            systemR.OpenNetwork(new AllPet.peer.tcp.PeerOption());
            systemR.OpenListen(new System.Net.IPEndPoint(System.Net.IPAddress.Any, 8888));
            systemR.RegistModule("recv", new Recv());
            systemR.Start();

            //客戶端
            var systemL = AllPet.Pipeline.PipelineSystem.CreatePipelineSystemV1(new AllPet.Common.Logger());

            systemL.RegistModule("send", new Send());
            systemL.OpenNetwork(new AllPet.peer.tcp.PeerOption());
            systemL.Start();

            //連接
            var remote    = new System.Net.IPEndPoint(System.Net.IPAddress.Parse("127.0.0.1"), 8888);
            var systemref = await systemL.ConnectAsync(remote);

            var module = systemL.GetPipeline(null, "this/send");

            while (true)
            {
                if (!betesting)
                {
                    Console.Write("通信速率测试(1=进行测试,exit=退出):>");
                    var line = Console.ReadLine();
                    if (line == "")
                    {
                        continue;
                    }
                    if (line == "exit")
                    {
                        systemR.CloseListen();
                        systemR.CloseNetwork();
                        systemR.Dispose();
                        systemL.Dispose();
                        break;
                    }
                    else if (line == "1")
                    {
                        betesting = true;
                        module.Tell(new byte[1]);
                    }
                }
                else
                {
                    //---------------------影响测试效率
                    //Console.Write("exit=退出):>");
                    var line = Console.ReadLine();
                    //if (line == "exit")
                    //{
                    //    systemR.CloseListen();
                    //    systemR.CloseNetwork();
                    //    systemR.Dispose();
                    //    systemL.Dispose();
                    //    break;
                    //}
                }
            }
        }
Example #39
0
 public ClosedEventArgs(System.Net.IPEndPoint iPEndPoint, CloseReason closeReason)
 {
     IPEndPoint  = iPEndPoint;
     CloseReason = closeReason;
 }
Example #40
0
 public ConnectEventArgs(System.Net.IPEndPoint iPEndPoint)
 {
     IPEndPoint = iPEndPoint;
 }
Example #41
0
 public RequestEventArgs(System.Net.IPEndPoint iPEndPoint, StringRequestInfo requestInfo)
 {
     IPEndPoint  = iPEndPoint;
     RequestInfo = requestInfo;
 }
Example #42
0
        public void Log(Severity severity, TraceLogger.LoggerType loggerType, string caller, string message, System.Net.IPEndPoint myIPEndPoint, Exception exception, int eventCode = 0)
        {
            lock (this)
            {
                if (entryCounts.ContainsKey(eventCode))
                {
                    entryCounts[eventCode]++;
                }
                else
                {
                    entryCounts.Add(eventCode, 1);
                }

                if (eventCode != lastLogCode)
                {
                    Console.WriteLine("{0} {1} - {2}", severity, eventCode, message);
                    lastLogCode = eventCode;
                }
            }
        }
Example #43
0
 /// <summary>
 /// Inisializes a new Client instance.
 /// </summary>
 /// <param name="localEP"></param>
 public Client(System.Net.IPEndPoint localEP) : base(localEP)
 {
 }
Example #44
0
        // 开始连接
        private void btnConnect_Click(object sender, EventArgs e)
        {
            if (this.txtLocalPort.Enabled)
            {
                // 新建连接
                if (string.IsNullOrEmpty(this.ipEditBox1.Text) || this.txtLocalPort.TextLength == 0)
                {
                    MessageBox.Show("请正确填写【IP】和【端口】设置");
                    return;
                }
                switch (this.comboBox1.SelectedIndex)
                {
                case 0:         // UDP
                    this.m_Udp = new UdpClient(this.m_Point = new System.Net.IPEndPoint(this.ipEditBox1.IP, int.Parse(this.txtLocalPort.Text)));
                    //uint IOC_IN = 0x80000000;
                    //uint IOC_VENDOR = 0x18000000;
                    //uint SIO_UDP_CONNRESET = IOC_IN | IOC_VENDOR | 12;
                    //this.m_Udp.Client.IOControl((int)SIO_UDP_CONNRESET, new byte[] { Convert.ToByte(false) }, null);
                    this.m_Udp.Client.IOControl(-1744830452, new byte[] { 0 }, null);
                    this.m_Udp.BeginReceive(this.udp_Callback, this.m_Udp);
                    this.label5.Text = "远端IP:";
                    this.comboBox2.Hide();
                    this.ipEditBox2.Show();
                    this.label7.Show();
                    this.txtRemotePort.Show();
                    this.panel4.Show();
                    break;

                case 1:         // Client
                    this.m_Tcp_C = new TcpClient();
                    try { this.m_Tcp_C.Connect(this.m_Point = new System.Net.IPEndPoint(this.ipEditBox1.IP, int.Parse(this.txtLocalPort.Text))); }
                    catch (Exception ex) { MessageBox.Show(ex.Message); return; }
                    SocketParam para = new SocketParam(this.m_Tcp_C.Client);
                    this.m_Tcp_C.Client.BeginReceive(para.Buffer, 0, 65536, SocketFlags.None, this.client_Callback, para);
                    break;

                default:        // Server
                    this.m_Tcp_S = new TcpListener(this.m_Point = new System.Net.IPEndPoint(this.ipEditBox1.IP, int.Parse(this.txtLocalPort.Text)));
                    this.m_Tcp_S.Start();
                    this.m_Tcp_S.BeginAcceptSocket(this.server_Callback, this.m_Tcp_S);
                    this.label5.Text = "客户端:";
                    this.comboBox2.Items.Clear();
                    this.comboBox2.Show();
                    this.ipEditBox2.Hide();
                    this.label7.Hide();
                    this.txtRemotePort.Hide();
                    this.panel4.Show();
                    break;
                }
                this.txtLocalPort.Enabled = this.ipEditBox1.Enabled = this.comboBox1.Enabled = false;
                this.btnConnect.Text      = "断开(&N)";
                this.chkAutoSend_CheckedChanged(null, null);
            }
            else
            {
                // 断开连接
                this.StopThread();  // 停止自动发送
                this.m_Mutex.WaitOne();
                this.panel4.Hide();
                switch (this.comboBox1.SelectedIndex)
                {
                case 0:         // UDP
                    this.m_Udp.Close();
                    (this.m_Udp as IDisposable).Dispose();
                    this.m_Udp = null;
                    break;

                case 1:         // Client
                    this.m_Tcp_C.Close();
                    (this.m_Tcp_C as IDisposable).Dispose();
                    this.m_Tcp_C = null;
                    break;

                default:        // Server
                    this.m_Mutex.ReleaseMutex();
                    for (int i = this.m_Clients.Count - 1; i >= 0; i--)
                    {
                        this.m_Clients[i].Dispose();
                    }
                    this.m_Mutex.WaitOne();
                    this.comboBox2.Items.Clear();
                    this.m_Tcp_S.Stop();
                    this.m_Tcp_S = null;
                    break;
                }
                this.m_Clients.Clear();
                this.m_Mutex.ReleaseMutex();
                this.txtLocalPort.Enabled = this.ipEditBox1.Enabled = this.comboBox1.Enabled = true;
                this.btnConnect.Text      = "连接(&N)";
            }
        }
Example #45
0
        /// <summary>
        /// The expected sequence of arguments:
        /// <list>
        /// <item>
        /// 1, [network-name] [options] [rpc-command] [rpc-params].
        /// </item>
        /// <item>
        /// 2, [network-name] [options] [api-controller "/" api-command] [api-params].
        /// </item>
        /// </list>
        /// </summary>
        public static void Main(string[] args)
        {
            try
            {
                // Preprocess the command line arguments
                var argList = new List <string>(args);

                string networkName = null;
                if (argList.Any())
                {
                    networkName = argList.First();
                    argList.RemoveAt(0);
                }

                var optionList = new List <string>();
                while ((argList.Any()) && (argList[0].StartsWith('-')))
                {
                    optionList.Add(argList[0]);
                    argList.RemoveAt(0);
                }

                string command = string.Empty;
                if (argList.Any())
                {
                    command = argList.First();
                    argList.RemoveAt(0);
                }

                var commandArgList = new List <string>(argList);

                // Display help if required.
                if (optionList.Contains("-help") || optionList.Contains("--help") || string.IsNullOrWhiteSpace(command))
                {
                    var builder = new StringBuilder();
                    builder.AppendLine("Usage:");
                    builder.AppendLine(" dotnet run <Stratis.Bitcoin.Cli/Stratis.Bitcoin.Cli.dll> [network-name] [options] <command> [arguments]");
                    builder.AppendLine();
                    builder.AppendLine("Command line arguments:");
                    builder.AppendLine();
                    builder.AppendLine("[network-name]                     Name of the network - e.g. \"stratis\", \"stratismain\", \"stratistest\", \"bitcoinmain\", \"bitcointest\".");
                    builder.AppendLine("[options]                          Options for the CLI (optional) - e.g. -help, -rpcuser, see below.");
                    builder.AppendLine("[command]                          Name of RPC method or API <controller>/<method>.");
                    builder.AppendLine("[arguments]                        Argument by position (RPC) or Name = Value pairs (API) (optional).");
                    builder.AppendLine();
                    builder.AppendLine("Options:");
                    builder.AppendLine("-help                              This help message");
                    builder.AppendLine("-rpcconnect=<ip>                   Send commands to node running on <ip> (default: 127.0.0.1)");
                    builder.AppendLine("-rpcport=<port>                    Connect to JSON-RPC on <port> (default for Stratis: 26174 or default for Bitcoin: 8332)");
                    builder.AppendLine("-rpcuser=<user>                    Username for JSON-RPC connections");
                    builder.AppendLine("-rpcpassword=<pw>                  Password for JSON-RPC connections");
                    builder.AppendLine();
                    builder.AppendLine("Examples:");
                    builder.AppendLine();
                    builder.AppendLine("dotnet run stratis Wallet/history WalletName=testwallet - Lists all the historical transactions of the wallet called 'testwallet'.");
                    builder.AppendLine("dotnet run stratis getinfo -rpcuser=stratistestuser -rpcpassword=stratistestpassword -rpcconnect=127.0.0.3 -rpcport=26174 - Displays general information about the Stratis node on the 127.0.0.3:26174, authenticating with the RPC specified user.");
                    builder.AppendLine("dotnet run bitcoin getbalance -rpcuser=btctestuser -rpcpassword=btctestpass - Displays the current balance of the opened wallet on the 127.0.0.1:8332 node, authenticating with the RPC specified user.");
                    Console.WriteLine(builder);
                    return;
                }

                // Determine API port.
                int     defaultRestApiPort = 0;
                Network network            = null;

                if (networkName.Contains("stratis"))
                {
                    defaultRestApiPort = 37221;
                    network            = NetworkRegistration.Register(new StratisMain());
                }
                else
                {
                    defaultRestApiPort = 37220;
                    network            = NetworkRegistration.Register(new BitcoinMain());
                }

                // API calls require both the contoller name and the method name separated by "/".
                // If this is not an API call then assume it is an RPC call.
                if (!command.Contains("/"))
                {
                    // Process RPC call.
                    try
                    {
                        string[] options = optionList.Append("-server").ToArray();

                        var nodeSettings = new NodeSettings(network, args: options);

                        var rpcSettings = new RpcSettings(nodeSettings);

                        // Find the binding to 127.0.0.1 or the first available. The logic in RPC settings ensures there will be at least 1.
                        System.Net.IPEndPoint nodeEndPoint = rpcSettings.Bind.FirstOrDefault(b => b.Address.ToString() == "127.0.0.1") ?? rpcSettings.Bind[0];
                        var rpcUri = new Uri($"http://{nodeEndPoint}");

                        // Process the command line RPC arguments
                        // TODO: this should probably be moved to the NodeSettings.FromArguments
                        if (options.GetValueOf("-rpcbind") != null)
                        {
                            rpcUri = new Uri($"http://{options.GetValueOf("-rpcbind")}");
                        }

                        if (options.GetValueOf("-rpcconnect") != null || options.GetValueOf("-rpcport") != null)
                        {
                            string rpcAddress = options.GetValueOf("-rpcconnect") ?? "127.0.0.1";

                            int rpcPort = rpcSettings.RPCPort;
                            int.TryParse(options.GetValueOf("-rpcport"), out rpcPort);

                            rpcUri = new Uri($"http://{rpcAddress}:{rpcPort}");
                        }
                        rpcSettings.RpcUser     = options.GetValueOf("-rpcuser") ?? rpcSettings.RpcUser;
                        rpcSettings.RpcPassword = options.GetValueOf("-rpcpassword") ?? rpcSettings.RpcPassword;

                        Console.WriteLine($"Connecting to the following RPC node: http://{rpcSettings.RpcUser}:{rpcSettings.RpcPassword}@{rpcUri.Authority}...");

                        // Initialize the RPC client with the configured or passed userid, password and endpoint.
                        var rpcClient = new RPCClient($"{rpcSettings.RpcUser}:{rpcSettings.RpcPassword}", rpcUri, network);

                        // Execute the RPC command
                        Console.WriteLine($"Sending RPC command '{command} {string.Join(" ", commandArgList)}' to '{rpcUri}'...");
                        RPCResponse response = rpcClient.SendCommand(command, commandArgList.ToArray());

                        // Return the result as a string to the console.
                        Console.WriteLine(response.ResultString);
                    }
                    catch (Exception err)
                    {
                        Console.WriteLine(err.Message);
                    }
                }
                else
                {
                    // Process API call.
                    using (var client = new HttpClient())
                    {
                        client.DefaultRequestHeaders.Accept.Clear();
                        client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
                        string url = $"http://localhost:{defaultRestApiPort}/api/{command}";
                        if (commandArgList.Any())
                        {
                            url += $"?{string.Join("&", commandArgList)}";
                        }
                        try
                        {
                            // Get the response.
                            Console.WriteLine($"Sending API command to {url}...");
                            string response = client.GetStringAsync(url).GetAwaiter().GetResult();

                            // Format and return the result as a string to the console.
                            Console.WriteLine(JsonConvert.SerializeObject(JsonConvert.DeserializeObject <object>(response), Formatting.Indented));
                        }
                        catch (Exception err)
                        {
                            Console.WriteLine(ExceptionToString(err));
                        }
                    }
                }
            }
            catch (Exception err)
            {
                // Report any errors to the console.
                Console.WriteLine(ExceptionToString(err));
            }
        }
        public static System.Net.NetworkInformation.NetworkInterface GetNetworkInterface(System.Net.IPEndPoint localEndPoint)
        {
            if (object.ReferenceEquals(localEndPoint, null))
            {
                throw new System.ArgumentNullException("localEndPoint");
            }

            return(GetNetworkInterface(localEndPoint.Address));
        }
Example #47
0
 private object OnRconConnection(System.Net.IPEndPoint ipEndPoint)
 {
     HookCalled("OnRconConnection");
     return(null);
 }
 public IPEndPoint()
 {
     Address   = "127.0.0.1";
     Port      = 0;
     _EndPoint = new System.Net.IPEndPoint(IPAddress.Loopback, 0);
 }
Example #49
0
 /// <summary>
 /// Event handler for host resolving
 /// </summary>
 /// <param name="hostnameIPEndPoint">server IP end point</param>
 private void echoClient_OnHostnameResolved(System.Net.IPEndPoint hostnameIPEndPoint)
 {
     Console.WriteLine(string.Format(Messages.HostnameResolved, arguments.FirstArgument, hostnameIPEndPoint.Address.ToString()));
     Console.WriteLine();
 }
Example #50
0
 public AltTcpListener(System.Net.IPEndPoint localEp) : base(localEp)
 {
 }
 public void Listen(System.Net.IPEndPoint endPoint)
 {
 }
 /// <summary>
 /// Creates the filter.
 /// </summary>
 /// <param name="appServer">The app server.</param>
 /// <param name="appSession">The app session.</param>
 /// <param name="remoteEndPoint">The remote end point.</param>
 /// <returns></returns>
 public IReceiveFilter <IWebSocketFragment> CreateFilter(IAppServer appServer, IAppSession appSession, System.Net.IPEndPoint remoteEndPoint)
 {
     return(new WebSocketHeaderReceiveFilter((IWebSocketSession)appSession));
 }
Example #53
0
 public System.Threading.Tasks.Task <int> SendAsync(byte[] datagram, int bytes, System.Net.IPEndPoint endPoint)
 {
     return(default(System.Threading.Tasks.Task <int>));
 }
Example #54
0
 public UdpReceiveResult(byte[] buffer, System.Net.IPEndPoint remoteEndPoint)
 {
     throw new System.NotImplementedException();
 }
Example #55
0
        public static Process GetProcessOfMatchingIPEndPoint(System.Net.IPEndPoint localEndpoint, System.Net.IPEndPoint remoteEndpoint)
        {
            int bufferSize = 0;

            // Getting the size of TCP table, that is returned in 'bufferSize' variable.
            uint result = NativeMethods.GetExtendedTcpTable(IntPtr.Zero, ref bufferSize, true, NativeMethods.AF_INET, NativeMethods.TCP_TABLE_CLASS.TCP_TABLE_OWNER_PID_ALL);

            // Allocating memory from the unmanaged memory of the process by using the
            // specified number of bytes in 'bufferSize' variable.
            IntPtr tcpTableRecordsPtr = Marshal.AllocHGlobal(bufferSize);

            try
            {
                // The size of the table returned in 'bufferSize' variable in previous
                // call must be used in this subsequent call to 'GetExtendedTcpTable'
                // function in order to successfully retrieve the table.
                result = NativeMethods.GetExtendedTcpTable(tcpTableRecordsPtr, ref bufferSize, true, NativeMethods.AF_INET, NativeMethods.TCP_TABLE_CLASS.TCP_TABLE_OWNER_PID_ALL);

                // Non-zero value represent the function 'GetExtendedTcpTable' failed,
                // hence empty list is returned to the caller function.
                if (result != 0)
                {
                    return(null);
                }

                // Marshals data from an unmanaged block of memory to a newly allocated
                // managed object 'tcpRecordsTable' of type 'MIB_TCPTABLE_OWNER_PID'
                // to get number of entries of the specified TCP table structure.
                NativeMethods.MIB_TCPTABLE_OWNER_PID tcpRecordsTable = (NativeMethods.MIB_TCPTABLE_OWNER_PID)
                                                                       Marshal.PtrToStructure(tcpTableRecordsPtr,
                                                                                              typeof(NativeMethods.MIB_TCPTABLE_OWNER_PID));
                IntPtr tableRowPtr = (IntPtr)((long)tcpTableRecordsPtr +
                                              Marshal.SizeOf(tcpRecordsTable.dwNumEntries));

                for (int row = 0; row < tcpRecordsTable.dwNumEntries; row++)
                {
                    NativeMethods.MIB_TCPROW_OWNER_PID tcpRow = (NativeMethods.MIB_TCPROW_OWNER_PID)Marshal.
                                                                PtrToStructure(tableRowPtr, typeof(NativeMethods.MIB_TCPROW_OWNER_PID));

                    System.Net.IPAddress localAddr  = new System.Net.IPAddress(tcpRow.localAddr);
                    System.Net.IPAddress remoteAddr = new System.Net.IPAddress(tcpRow.remoteAddr);
                    UInt16 localPort = BitConverter.ToUInt16(new byte[2] {
                        tcpRow.localPort[1], tcpRow.localPort[0]
                    }, 0);
                    UInt16 remotePort = BitConverter.ToUInt16(new byte[2] {
                        tcpRow.remotePort[1], tcpRow.remotePort[0]
                    }, 0);

                    if ((localEndpoint.Address.ToString() == localAddr.ToString()) &&
                        (localEndpoint.Port == localPort) &&
                        (remoteEndpoint.Address.ToString() == remoteAddr.ToString()) &&
                        (remoteEndpoint.Port == remotePort))
                    {
                        int pid = tcpRow.owningPid;
                        return(Process.GetProcessById(pid));
                    }

                    tableRowPtr = (IntPtr)((long)tableRowPtr + Marshal.SizeOf(tcpRow));
                }
            }
            catch (OutOfMemoryException)
            {
                return(null);
            }
            catch (Exception)
            {
                return(null);
            }
            finally
            {
                Marshal.FreeHGlobal(tcpTableRecordsPtr);
            }

            return(null);
        }
 public IPEndPoint(IPAddress address, int port)
 {
     Address   = address.ToString();
     Port      = port;
     _EndPoint = new System.Net.IPEndPoint(address, port);
 }
Example #57
0
        /// <summary>
        /// The expected sequence of arguments:
        /// <list>
        /// <item>
        /// 1, [network-name] [options] [rpc-command] [rpc-params].
        /// </item>
        /// <item>
        /// 2, [network-name] [options] [api-controller "/" api-command] [api-params].
        /// </item>
        /// </list>
        /// </summary>
        public static void Main(string[] args)
        {
            try
            {
                // Preprocess the command line arguments
                var argList = new List <string>(args);

                string networkName = null;
                if (argList.Any())
                {
                    networkName = argList.First();
                    argList.RemoveAt(0);
                }

                var optionList = new List <string>();
                while ((argList.Any()) && (argList[0].StartsWith('-')))
                {
                    optionList.Add(argList[0]);
                    argList.RemoveAt(0);
                }

                string method = "";
                if (argList.Any())
                {
                    method = argList.First().ToUpper();
                    if (method == "GET" || method == "POST" || method == "DELETE")
                    {
                        argList.RemoveAt(0);
                    }
                    else
                    {
                        method = "";
                    }
                }

                string command = string.Empty;
                if (argList.Any())
                {
                    command = argList.First();
                    argList.RemoveAt(0);
                }

                var commandArgList = new List <string>(argList);

                // Display help if required.
                if (optionList.Contains("-help") || optionList.Contains("--help") || string.IsNullOrWhiteSpace(command))
                {
                    var builder = new StringBuilder();
                    builder.AppendLine("Usage:");
                    builder.AppendLine(" dotnet run <Blockcore.Cli/Blockcore.Cli.dll> [network-name] [options] [method] <command> [arguments]");
                    builder.AppendLine();
                    builder.AppendLine("Command line arguments:");
                    builder.AppendLine();
                    builder.AppendLine("[network-name]                     Name of the network - e.g. \"stratis\" or \"bitcoin\".");
                    builder.AppendLine("[options]                          Options for the CLI (optional) - e.g. -help, -rpcuser, see below.");
                    builder.AppendLine("[method]                           Method to use for API calls - 'GET', 'POST' or 'DELETE'.");
                    builder.AppendLine("[command]                          Name of RPC method or API <controller>/<method>.");
                    builder.AppendLine("[arguments]                        Argument by position (RPC) or Name = Value pairs (API) (optional).");
                    builder.AppendLine();
                    builder.AppendLine("Options:");
                    builder.AppendLine("-help                              This help message");
                    builder.AppendLine("-rpcconnect=<ip>                   Send commands to node running on <ip> (default: 127.0.0.1)");
                    builder.AppendLine("-rpcport=<port>                    Connect to JSON-RPC on <port> (default for Stratis: 26174 or default for Bitcoin: 8332)");
                    builder.AppendLine("-rpcuser=<user>                    Username for JSON-RPC connections");
                    builder.AppendLine("-rpcpassword=<pw>                  Password for JSON-RPC connections");
                    builder.AppendLine();
                    builder.AppendLine("Examples:");
                    builder.AppendLine();
                    builder.AppendLine("dotnet run stratis -testnet GET Wallet/history WalletName=testwallet - Lists all the historical transactions of the wallet called 'testwallet' on the stratis test network.");
                    builder.AppendLine("dotnet run stratis -rpcuser=stratistestuser -rpcpassword=stratistestpassword -rpcconnect=127.0.0.3 -rpcport=26174 getinfo - Displays general information about the Stratis node on the 127.0.0.3:26174, authenticating with the RPC specified user.");
                    builder.AppendLine("dotnet run bitcoin -rpcuser=btctestuser -rpcpassword=btctestpass getbalance - Displays the current balance of the opened wallet on the 127.0.0.1:8332 node, authenticating with the RPC specified user.");
                    Console.WriteLine(builder);
                    return;
                }

                // Determine API port.
                NetworksSelector networksSelector = null;

                networksSelector = Blockcore.Networks.Bitcoin.Networks.Bitcoin;

                // API calls require both the contoller name and the method name separated by "/".
                // If this is not an API call then assume it is an RPC call.
                if (!command.Contains("/"))
                {
                    // Process RPC call.
                    try
                    {
                        string[] options      = optionList.Append("-server").ToArray();
                        var      nodeSettings = new NodeSettings(networksSelector: networksSelector, args: options)
                        {
                            MinProtocolVersion = ProtocolVersion.POS_PROTOCOL_VERSION
                        };

                        var     rpcSettings = new RpcSettings(nodeSettings);
                        Network network     = nodeSettings.Network;

                        // Find the binding to 127.0.0.1 or the first available. The logic in RPC settings ensures there will be at least 1.
                        System.Net.IPEndPoint nodeEndPoint = rpcSettings.Bind.FirstOrDefault(b => b.Address.ToString() == "127.0.0.1") ?? rpcSettings.Bind[0];
                        var rpcUri = new Uri($"http://{nodeEndPoint}");

                        // Process the command line RPC arguments
                        // TODO: this should probably be moved to the NodeSettings.FromArguments
                        if (options.GetValueOf("-rpcbind") != null)
                        {
                            rpcUri = new Uri($"http://{options.GetValueOf("-rpcbind")}");
                        }

                        if (options.GetValueOf("-rpcconnect") != null || options.GetValueOf("-rpcport") != null)
                        {
                            string rpcAddress = options.GetValueOf("-rpcconnect") ?? "127.0.0.1";

                            int rpcPort = rpcSettings.RPCPort;
                            int.TryParse(options.GetValueOf("-rpcport"), out rpcPort);

                            rpcUri = new Uri($"http://{rpcAddress}:{rpcPort}");
                        }
                        rpcSettings.RpcUser     = options.GetValueOf("-rpcuser") ?? rpcSettings.RpcUser;
                        rpcSettings.RpcPassword = options.GetValueOf("-rpcpassword") ?? rpcSettings.RpcPassword;

                        Console.WriteLine($"Connecting to the following RPC node: http://{rpcSettings.RpcUser}:{rpcSettings.RpcPassword}@{rpcUri.Authority}.");

                        // Initialize the RPC client with the configured or passed userid, password and endpoint.
                        var rpcClient = new RPCClient($"{rpcSettings.RpcUser}:{rpcSettings.RpcPassword}", rpcUri, network);

                        // Execute the RPC command
                        Console.WriteLine($"Sending RPC command '{command} {string.Join(" ", commandArgList)}' to '{rpcUri}'.");
                        RPCResponse response = rpcClient.SendCommand(command, commandArgList.ToArray());

                        // Return the result as a string to the console.
                        Console.WriteLine(response.ResultString);
                    }
                    catch (Exception err)
                    {
                        Console.WriteLine(err.Message);
                    }
                }
                else
                {
                    // Process API call.
                    string[] options      = optionList.ToArray();
                    var      nodeSettings = new NodeSettings(networksSelector: networksSelector, args: options);

                    var apiSettings = new NodeHostSettings(nodeSettings);

                    string url = $"http://localhost:{apiSettings.ApiPort}/api".AppendPathSegment(command);

                    object commandArgObj = GetAnonymousObjectFromDictionary(commandArgList
                                                                            .Select(a => a.Split('='))
                                                                            .ToDictionary(a => a[0], a => a[1]));

                    HttpResponseMessage httpResponse;

                    switch (method)
                    {
                    case "POST":
                        httpResponse = CallApiPost(url, commandArgObj);
                        break;

                    case "DELETE":
                        httpResponse = CallApiDelete(url, commandArgObj);
                        break;

                    default:
                        httpResponse = CallApiGet(url, commandArgObj);
                        break;
                    }

                    var response = httpResponse.Content.ReadAsStringAsync().GetAwaiter().GetResult();

                    // Format and return the result as a string to the console.
                    Console.WriteLine(JsonConvert.SerializeObject(JsonConvert.DeserializeObject <object>(response), Formatting.Indented));
                }
            }
            catch (Exception err)
            {
                // Report any errors to the console.
                Console.WriteLine(ExceptionToString(err));
            }
        }
Example #58
0
 public UdpClient(System.Net.IPEndPoint localEP)
 {
 }
        public void RefreshServerStatistics()
        {
            if (_isRefreshing == true)
            {
                return;
            }

            // It's not the end of the world if a call makes it through on a race condition.
            // We're just going to try to stop it from spamming the cache servers if one of
            // them takes longer than 5 seconds to respond.
            //lock (_syncLock)
            //{
            _isRefreshing = true;

            try
            {
                for (int serverIndex = 0; serverIndex < _serversToMonitor.Count; serverIndex++)
                {
                    Server server = _serversToMonitor[serverIndex];

                    if (_stopRequested == true)
                    {
                        break;
                    }

                    //foreach (Instance instance in server.Instances)
                    for (int instanceIndex = 0; instanceIndex < server.Instances.Count; instanceIndex++)
                    {
                        Instance instance = server.Instances[instanceIndex];

                        if (_stopRequested == true)
                        {
                            break;
                        }

                        MemcachedClient       memcachedClient;
                        System.Net.IPEndPoint serverEndPoint = new System.Net.IPEndPoint(System.Net.Dns.GetHostEntry(server.ServerName).AddressList[0], instance.TcpPort);

                        if (_memcachedConnections.ContainsKey(instance) == false)
                        {
                            MemcachedClientConfiguration config = new MemcachedClientConfiguration();
                            config.Servers.Add(serverEndPoint);
                            config.SocketPool.ConnectionTimeout = new TimeSpan(0, 0, 3);

                            //config.SocketPool.

                            memcachedClient = new MemcachedClient(config);

                            _memcachedConnections.Add(instance, memcachedClient);
                        }
                        else
                        {
                            memcachedClient = _memcachedConnections[instance];
                        }

                        State serviceState = State.Unknown;

                        try
                        {
                            serviceState = instance.GetServiceState(server);
                        }
                        catch (Exception ex)
                        {
                            // Leave the state as unknown.
                            Debug.WriteLine(ex);
                        }

                        ServerStats        serverStats        = memcachedClient.Stats();
                        InstanceStatistics instanceStatistics = new InstanceStatistics(serverEndPoint, server, instance, serverStats, serviceState);

                        if (InstanceUpdated != null)
                        {
                            InstanceUpdated(server, instance, instanceStatistics);
                        }
                    }
                }
            }
            finally
            {
                _isRefreshing = false;
            }
            //}
        }
Example #60
0
 /// <summary>
 /// Called when this WebSockets Server accepts a new WebSockets client.
 /// </summary>
 /// <param name="context">The context.</param>
 /// <param name="localEndPoint">The local endpoint.</param>
 /// <param name="remoteEndPoint">The remote endpoint.</param>
 protected abstract void OnClientConnected(
     IWebSocketContext context,
     System.Net.IPEndPoint localEndPoint,
     System.Net.IPEndPoint remoteEndPoint);