ToString() public method

public ToString ( ) : string
return string
Example #1
0
        public void messageReceiver()
        {
            UdpClient listener = new UdpClient(receivingPort);
            IPEndPoint groupEP = new IPEndPoint(IPAddress.Any, receivingPort);
            string received_data;
            byte[] receive_byte_array;

            try
            {
                while (true)
                {
                    Console.WriteLine("Waiting for broadcast");
                    receive_byte_array = listener.Receive(ref groupEP);
                    Console.WriteLine("Received a broadcast from {0}", groupEP.ToString());
                    string[] IPHolster = groupEP.ToString().Split(':');
                    checkedIPAddresses.Add(IPHolster[0]);
                    received_data = Encoding.ASCII.GetString(receive_byte_array, 0, receive_byte_array.Length);
                    Console.WriteLine("data follows \n{0}\n\n", received_data);
                }
            }
            catch (Exception e)
            {
                Console.WriteLine(e.ToString());
            }
        }
Example #2
0
        static void Main(string[] args)
        {
            byte[] data = new byte[1024];
            IPEndPoint ipep = new IPEndPoint(IPAddress.Any, 2005);
            UdpClient newsock = new UdpClient(ipep);

            Console.WriteLine("Waiting for a client...");

            IPEndPoint sender = new IPEndPoint(IPAddress.Any, 0);

            data = newsock.Receive(ref sender);

            Console.WriteLine("Message received from {0}:", sender.ToString());
            Console.WriteLine(Encoding.ASCII.GetString(data, 0, data.Length));

            string welcome = "Welcome to my test server";
            data = Encoding.ASCII.GetBytes(welcome);
            newsock.Send(data, data.Length, sender);

            while (true)
            {
                data = newsock.Receive(ref sender);

                Console.WriteLine("Message received from {0}:", sender.ToString());
                Console.WriteLine(Encoding.ASCII.GetString(data, 0, data.Length));
                newsock.Send(data, data.Length, sender);
            }
        }
Example #3
0
		protected NodeBase(ICluster owner, IPEndPoint endpoint, IFailurePolicy failurePolicy, ISocket socket)
		{
			this.owner = owner;
			this.endpoint = endpoint;
			this.socket = socket;
			this.failurePolicy = failurePolicy;
			this.name = endpoint.ToString();

			failLock = new Object();
			writeQueue = new ConcurrentQueue<Data>();
			readQueue = new Queue<Data>();

			mustReconnect = true;
			IsAlive = true;

			counterEnqueuePerSec = Metrics.Meter("node write enqueue/sec", endpoint.ToString(), Interval.Seconds);
			counterDequeuePerSec = Metrics.Meter("node write dequeue/sec", endpoint.ToString(), Interval.Seconds);
			counterOpReadPerSec = Metrics.Meter("node op read/sec", endpoint.ToString(), Interval.Seconds);
			counterWriteQueue = Metrics.Counter("write queue length", endpoint.ToString());
			counterReadQueue = Metrics.Counter("read queue length", endpoint.ToString());

			counterWritePerSec = Metrics.Meter("node write/sec", endpoint.ToString(), Interval.Seconds);
			counterErrorPerSec = Metrics.Meter("node in error/sec", endpoint.ToString(), Interval.Seconds);
			counterItemCount = Metrics.Counter("commands", endpoint.ToString());
			gaugeSendSpeed = Metrics.Gauge("send speed", endpoint.ToString());
		}
        public ServerSession(IPEndPoint ipEndPoint)
        {
            string url = "http://" + ipEndPoint.ToString() + "/api/general/getname";

            new HttpGetRequest<ServerName>(url, next);

            url = "http://" + ipEndPoint.ToString() + "/api/account/login";

            new HttpPostRequest<LoginInput,LoginOutput>(url, next2,new LoginInput("123","placek"));
        }
Example #5
0
 static void Receiver_Received2(System.Net.IPEndPoint client, byte[] data)
 {
     if (data != null && data.Length > 0)
     {
         Console.WriteLine("收到来自消费型客户端[" + client.ToString() + "]的数据共" + data.Length + "字节。");
     }
     else
     {
         Console.WriteLine("收到来自消费型客户端[" + client.ToString() + "]的消息,无数据。");
     }
 }
 public static Exception ConvertListenException(SocketException socketException, IPEndPoint localEndpoint)
 {
     if (socketException.ErrorCode == 6)
     {
         return new CommunicationObjectAbortedException(socketException.Message, socketException);
     }
     if (socketException.ErrorCode == 0x2740)
     {
         return new AddressAlreadyInUseException(System.ServiceModel.SR.GetString("TcpAddressInUse", new object[] { localEndpoint.ToString() }), socketException);
     }
     return new CommunicationException(System.ServiceModel.SR.GetString("TcpListenError", new object[] { socketException.ErrorCode, socketException.Message, localEndpoint.ToString() }), socketException);
 }
Example #7
0
        public Node(IPEndPoint endpoint, IMessageBusFactory messageBusFactory)
        {
            _messageBusFactory = messageBusFactory;
            this.Nodes = new Dictionary<string, HashTableEntry>();
            this.Entry = new HashTableEntry();
            this.Endpoint = endpoint;
            this.Entry.Address = endpoint.ToString();

            hash = MD5.Create();
            byte[] bytes = Encoding.ASCII.GetBytes(endpoint.ToString());
            this.Entry.NodeId = new BigInteger(hash.ComputeHash(bytes)).ToString();
            this.Entry.LastSeen = DateTime.MinValue;
        }
Example #8
0
        public Node(IPEndPoint endpoint)
        {
            this.Nodes = new Dictionary<string, HashTableEntry>();
            this.Entry = new HashTableEntry();
            this.Entry.Address = endpoint.ToString();

            hash = MD5.Create();
            byte[] bytes = Encoding.ASCII.GetBytes(endpoint.ToString());
            this.Entry.NodeId = new BigInteger(hash.ComputeHash(bytes)).ToString();
            this.Entry.LastUpdated = DateTime.MinValue;

            this.Nodes.Add(this.Entry.NodeId, this.Entry);
        }
Example #9
0
        public void Run()
        {
            while (true)
            {
                remoteHost = new IPEndPoint(IPAddress.Any, 0);

                Byte[] data = conn.Receive(ref remoteHost);

                Console.WriteLine("{0}: Received a connection from:{1}", prog, remoteHost.ToString());

                rpcCracker cracker = new rpcCracker(data);

                //cracker.Dump("Received");

                rpcPacker reply = CrackRPC(cracker);

                Console.WriteLine("{0}: Sending a reply to:{1}", prog, remoteHost.ToString());

                //reply.Dump("Sending");

                int sent = conn.Send(reply.Data, (int)reply.Length, remoteHost);

                if (sent != (int)reply.Length)
                    Console.WriteLine("*** Didn't send all.  Length:{0}, sent:{1}", reply.Length, sent);
            }
        }
        private static uint[] GenerateDefaultKeyRanges(IPEndPoint endPoint, int numberOfKeys)
        {
            const int KeyLength = 4;
            const int PartCount = 1; // (ModifiedFNV.HashSize / 8) / KeyLength; // HashSize is in bits, uint is 4 byte long

            var k = new uint[PartCount * numberOfKeys];

            // every server is registered numberOfKeys times
            // using UInt32s generated from the different parts of the hash
            // i.e. hash is 64 bit:
            // 00 00 aa bb 00 00 cc dd
            // server will be stored with keys 0x0000aabb & 0x0000ccdd
            // (or a bit differently based on the little/big indianness of the host)
            string address = endPoint.ToString();
            var fnv = new FNV1a();

            for (int i = 0; i < numberOfKeys; i++)
            {
                byte[] data = fnv.ComputeHash(Encoding.ASCII.GetBytes(String.Concat(address, "-", i)));

                for (int h = 0; h < PartCount; h++)
                {
                    k[i * PartCount + h] = BitConverter.ToUInt32(data, h * KeyLength);
                }
            }

            return k;
        }
Example #11
0
        internal void DoSendDiscoveryRequest(
            IPEndPoint endPoint,
            bool useBroadcast,
            NetDiscoveryRequest request,
            float interval,
            float timeout)
        {
            if (!m_netBase.m_isBound)
                m_netBase.Start();

            if (request == null)
            {
                m_netBase.LogVerbose("Creating discovery request " + m_nextRequestNumber);
                request = new NetDiscoveryRequest(endPoint, m_nextRequestNumber++, useBroadcast, interval, timeout);
                if (m_requests == null)
                    m_requests = new List<NetDiscoveryRequest>();
                m_requests.Add(request);
            }

            string appIdent = m_netBase.m_config.ApplicationIdentifier;
            NetBuffer data = new NetBuffer(appIdent.Length + 8);

            // write app identifier
            data.Write(appIdent);

            // write netbase identifier to avoid self-discovery
            data.Write(m_netBase.m_randomIdentifier);

            // write request number
            data.Write((ushort)request.Number);

            m_netBase.LogWrite("Discovering " + endPoint.ToString() + "...");
            m_netBase.QueueSingleUnreliableSystemMessage(NetSystemType.Discovery, data, endPoint, useBroadcast);
        }
Example #12
0
		public void ContentEncoding_Disposed ()
		{
			IPEndPoint ep = new IPEndPoint (IPAddress.Loopback, 8000);
			string url = "http://" + ep.ToString () + "/test/";

			using (SocketResponder responder = new SocketResponder (ep, new SocketRequestHandler (FullResponseHandler))) {
				responder.Start ();

				HttpWebRequest req = (HttpWebRequest) WebRequest.Create (url);
				req.Method = "GET";
				req.Timeout = 2000;
				req.ReadWriteTimeout = 2000;
				req.KeepAlive = false;

				HttpWebResponse resp = (HttpWebResponse) req.GetResponse ();
				((IDisposable) resp).Dispose ();

				try {
					string enc = resp.ContentEncoding;
					Assert.Fail ("#1:" + enc);
				} catch (ObjectDisposedException ex) {
					Assert.AreEqual (typeof (ObjectDisposedException), ex.GetType (), "#2");
					Assert.IsNull (ex.InnerException, "#3");
					Assert.IsNotNull (ex.Message, "#4");
					Assert.AreEqual (typeof (HttpWebResponse).FullName, ex.ObjectName, "#5");
				}
			}
		}
Example #13
0
        public Form1()
            : base("Desktop Viewer", 20, 20, 640, 480)
        {
            //fAutoScale = true;

            // Create the backing buffer to retain the image
            fBackingBuffer = new GDIDIBSection(1600, 1200);

            // 1.  Show a dialog box to allow the user to type in the 
            // group IP address and port number.
            HostForm groupForm = new HostForm();
            groupForm.ShowDialog();

            // 2. Get the address and port from the form, and use
            // them to setup the MultiSession object
            string groupIP = groupForm.groupAddressField.Text;
            int groupPort = int.Parse(groupForm.groupPortField.Text);
            IPEndPoint ipep = new IPEndPoint(IPAddress.Parse(groupIP), groupPort);

            Title = "Desktop Viewer - " + ipep.ToString();

            fSession = new MultiSession(Guid.NewGuid().ToString(), ipep);
            fSketchChannel = fSession.CreateChannel(PayloadType.dynamicPresentation);

            // 3. Setup the chunk decoder so we can receive new images
            // when they come in
            fChunkDecoder = new GraphPortChunkDecoder(fBackingBuffer, fSketchChannel);
            fChunkDecoder.PixBltPixelBuffer24Handler += this.PixBltPixelBuffer24;
            fChunkDecoder.PixBltLumbHandler += this.PixBltLum24;

            fUserIOChannel = fSession.CreateChannel(PayloadType.xApplication2);
            fUserIOEncoder = new UserIOChannelEncoder(fUserIOChannel);
            fUserIODecoder = new UserIOChannelDecoder(fUserIOChannel);
            fUserIODecoder.MoveCursorEvent += MoveCursor;
        }
Example #14
0
        private void Form1_Load(object sender, EventArgs e)
        {
            UdpClient udpServer = new UdpClient(11000);
            IsUDPActive = true;

            Thread thrd_UDPServer = new Thread(delegate()
            {

                while (IsUDPActive)
                {
                    var remoteEP = new IPEndPoint(IPAddress.Any, 11000);
                    var data = udpServer.Receive(ref remoteEP); // listen on port 11000
                    LogMessage("receive data from " + remoteEP.ToString() + ":" + Encoding.ASCII.GetString(data));
                    string payload = devicename + "," + mac + "," + GetLocalIPAddress() + "," + tcpPort;
                    string rcvddata = Encoding.ASCII.GetString(data);
                    if (rcvddata.ToLower().Contains("ping cielo"))
                    {
                        udpServer.Send(Encoding.ASCII.GetBytes(payload), payload.Length, remoteEP); // reply back
                        // IsUDPActive = false;
                        objServer = new SocketServerAsync(tcpPort);
                        objServer.OnSocketConnected += objServer_OnSocketConnected;
                        objServer.OnMessageReceived += objServer_OnMessageReceived;
                    }
                }
            });
            thrd_UDPServer.IsBackground = false;
            thrd_UDPServer.Start();


        }
Example #15
0
        public static void Start()
        {
            AppDomain.CurrentDomain.UnhandledException += UnhandledExceptionTrapper;

            listener = new Socket(AddressFamily.InterNetwork,
                SocketType.Dgram, ProtocolType.Udp);

            listener.Bind(new IPEndPoint(IPAddress.Any, PORT));

            Console.WriteLine("Waiting for a connection..." + GetLocalIpAddress());

            while (true) {

                EndPoint remoteEndPoint = new IPEndPoint(IPAddress.Any, 0);
                StateObject state = new StateObject();
                state.WorkSocket = listener;
                listener.ReceiveFrom(state.Buffer, ref remoteEndPoint);
                var rawMessage = Encoding.UTF8.GetString(state.Buffer);
                var messages = rawMessage.Split(';');

                if (messages.Length > 1) {
                    var command = messages[0];
                    var deviceName = messages[1];
                    Console.WriteLine("Command is received from Device Name +"+deviceName+"+");
                    string[] portno = remoteEndPoint.ToString().Split(':');
                    Send(portno[1],remoteEndPoint);

                }
            }
        }
Example #16
0
        /// <summary>
        /// Default constructor.
        /// </summary>
        /// <param name="stack">Owner stack.</param>
        /// <param name="isServer">Specifies if flow is server or client flow.</param>
        /// <param name="localEP">Local IP end point.</param>
        /// <param name="remoteEP">Remote IP end point.</param>
        /// <param name="transport">SIP transport.</param>
        /// <exception cref="ArgumentNullException">Is raised when <b>stack</b>,<b>localEP</b>,<b>remoteEP</b>  or <b>transport</b> is null reference.</exception>
        /// <exception cref="ArgumentException">Is raised whena any of the arguments has invalid value.</exception>
        internal SIP_Flow(SIP_Stack stack,bool isServer,IPEndPoint localEP,IPEndPoint remoteEP,string transport)
        {
            if(stack == null){
                throw new ArgumentNullException("stack");
            }
            if(localEP == null){
                throw new ArgumentNullException("localEP");
            }
            if(remoteEP == null){
                throw new ArgumentNullException("remoteEP");
            }
            if(transport == null){
                throw new ArgumentNullException("transport");
            }

            m_pStack    = stack;
            m_IsServer  = isServer;
            m_pLocalEP  = localEP;
            m_pRemoteEP = remoteEP;
            m_Transport = transport.ToUpper();

            m_CreateTime   = DateTime.Now;
            m_LastActivity = DateTime.Now;
            m_ID           = m_pLocalEP.ToString() + "-" + m_pRemoteEP.ToString() + "-" + m_Transport;
            m_pMessage     = new MemoryStream();
        }
Example #17
0
 public Server(string hostname, int port, int clientPort)
 {
     endPoint = new IPEndPoint(IPAddress.Parse(hostname), clientPort);
     server = new UdpClient(port);
     Console.WriteLine($"Server start listenning. Local End Point: {endPoint.ToString()}");
     ProcessConnection();
 }
        private void endReceive(IAsyncResult ar)
        {
            IPEndPoint ip = new IPEndPoint(IPAddress.IPv6Any, 00000);
            byte[] data = client.EndReceive(ar, ref ip);
            Packet p = new Packet(data, ip);
            from = ip;
            Log.Debug("AYY");
            if (p.OperationID == operationID)
            {
                recv.Add(p.HandshakeID, p.GetCleanData());
                Packet reply = p.MakeReply();
                client.Send(reply._data, reply._data.Length, ip);
                Log.Info(string.Format("Received {0} bytes from {1}.", new object[] { data.Length, ip.ToString() }));
                currentCount++;
            }
            else
            {
                Log.Error(string.Format("Invalid packet Operation ID {0} expected {1}.", new object[] { p.OperationID.ToString("X"), operationID.ToString("X") }));
            }

            if(currentCount != totalCount)
            {
                client.BeginReceive(endReceive, null);
            }
            else
            {
                Log.Info(string.Format("R operation {0} has been completed successfully.", operationID.ToString("X")));
                Packet packet = GetPacket();
                client.Close();
                UdpPacketRouter.QuitReceiveOp(operationID);
                callBack(packet);
            }
        }
Example #19
0
        public static int Main()
        {
            bool done = false;
            double received_data;
            byte[] receive_byte_array;

            UdpClient listener = new UdpClient(listenPort);
            IPEndPoint groupEP = new IPEndPoint(IPAddress.Any, listenPort);

            Console.WriteLine("Waiting for broadcast");

            try
            {
                while (!done)
                {
                    // This is the line of code that receives the broadcase message. It calls the receive function
                    // from the object listener (class UdpClient). It passes to listener the end point groupEP. It
                    // puts the data from the broadcast message into the byte array named received_byte_array. Note
                    // that this is a synchronous or blocking call.

                    receive_byte_array = listener.Receive(ref groupEP);
                    Console.WriteLine("Received a broadcast from {0}", groupEP.ToString());
                    received_data = System.BitConverter.ToDouble(receive_byte_array, 0);
                    Console.WriteLine("Data: {0} \n", received_data);
                }
            }
            catch (Exception e)
            {
                Console.WriteLine(e.ToString());
            }
            listener.Close();
            return 0;
        }
        private Dictionary<string, DateTime> m_connectionFailures = new Dictionary<string, DateTime>(); // Tracks sockets that have had a connection failure on them to avoid endless re-connect attmepts.

        public SIPTCPChannel(IPEndPoint endPoint)
        {
            m_localSIPEndPoint = new SIPEndPoint(SIPProtocolsEnum.tcp, endPoint);
            LocalTCPSockets.Add(endPoint.ToString());
            m_isReliable = true;
            Initialise();
        }
Example #21
0
        public void Start()
        {
            try
            {
                byte[] buffer = new byte[4096];
                EndPoint remoteEndPoint = new IPEndPoint(IPAddress.Any, 0);

                logger.Debug("ICMPListener receive thread starting.");

                while (!m_stop)
                {
                    int bytesRead = m_icmpListener.ReceiveFrom(buffer, ref remoteEndPoint);
                    logger.Debug("ICMPListener received " + bytesRead + " from " + remoteEndPoint.ToString());

                    if (Receive != null)
                    {
                        Receive(new ICMP(buffer, bytesRead), remoteEndPoint as IPEndPoint);
                    }

                    //m_icmpListener.BeginReceive(buffer, 0, buffer.Length, SocketFlags.None, this.ReceiveRawPacket, buffer);
                }

                logger.Debug("ICMPListener receive thread stopped.");
            }
            catch (Exception excp)
            {
                logger.Error("Exception ICMPListener Start. " + excp.Message);
                throw;
            }
        }
Example #22
0
        private static void StartListener()
        {
            bool done = false;

            UdpClient listener = new UdpClient(listenPort);
            IPEndPoint groupEP = new IPEndPoint(IPAddress.Any, listenPort);

            try
            {
                while (!done)
                {
                    Console.WriteLine("Waiting for broadcast");
                    byte[] bytes = listener.Receive(ref groupEP);

                    Console.WriteLine("Received broadcast from {0} :\n {1}\n",
                        groupEP.ToString(),
                        Encoding.ASCII.GetString(bytes, 0, bytes.Length));
                }

            }
            catch (Exception e)
            {
                Console.WriteLine(e.ToString());
            }
            finally
            {
                listener.Close();
            }
        }
Example #23
0
    // OnGUI
    void OnGUI()
    {
        if (disconnected)
        {
            GUIHelper.BeginBox(400, 72);
            GUILayout.Label("Disconnected from the game server.");
            if (server != null)
            {
                using (new GUIHorizontalCenter()) {
                    if (GUIHelper.Button("Reconnect"))
                    {
                        LogManager.General.Log("Reconnecting to " + server.ToString());

                        if (InGameLobby.instance != null)
                        {
                            // Real server
                            InGameLobby.instance.ConnectToGameServerByIPEndPoint(server);
                        }
                        else
                        {
                            // Test server
                            Application.LoadLevel("Client");
                            uLink.Network.Connect(server);
                        }
                    }
                }
            }

            GUIHelper.EndBox();
        }
    }
Example #24
0
        public void checkCapacity(String ip,int port,int compacity,int compacityLeft,bool isAlert)
        {
            try
            {
                //开始连接

                clientSocket = new UdpClient();
                IPEndPoint iep = new IPEndPoint(IPAddress.Parse(ip), port);
                byte[] sendBytes = this.sendBytes(compacity, compacityLeft, isAlert);
                Console.WriteLine(sendBytes[0]+"   "+sendBytes[11]);

                clientSocket.Send(sendBytes, sendBytes.Length, iep);
                byte[] bytes = clientSocket.Receive(ref iep);

                string str = Encoding.UTF8.GetString(bytes, 0, bytes.Length);
                string message = "来自" + iep.ToString() + "的消息";
                Console.WriteLine("message is:"+message);

            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.ToString());
            }
            finally {
                if (clientSocket != null) {
                    clientSocket.Close();
                }

            }
        }
Example #25
0
        static void Main(String[] args)
        {
            CancellationTokenSource cancellation = new CancellationTokenSource();

            var endpoint = new IPEndPoint(IPAddress.Any, 8001);
            WebSocketListener server = new WebSocketListener(endpoint, new WebSocketListenerOptions() { SubProtocols = new[] {"chat"} });
            var rfc6455 = new vtortola.WebSockets.Rfc6455.WebSocketFactoryRfc6455(server);
            rfc6455.MessageExtensions.RegisterExtension(new WebSocketDeflateExtension());
            server.Standards.RegisterStandard(rfc6455);
            server.Start();

            Log("Rx Chat Server started at " + endpoint.ToString());

            var chatSessionObserver = new ChatSessionsObserver(new ChatRoomManager());

            Observable.FromAsync(server.AcceptWebSocketAsync)
                      .Select(ws => new ChatSession(ws) 
                              { 
                                  In = Observable.FromAsync<dynamic>(ws.ReadDynamicAsync)
                                                 .DoWhile(() => ws.IsConnected)
                                                 .Where(msg => msg != null), 
                    
                                  Out = Observer.Create<dynamic>(ws.WriteDynamic) 
                              })
                      .DoWhile(() => server.IsStarted && !cancellation.IsCancellationRequested)
                      .Subscribe(chatSessionObserver);
         
            Console.ReadKey(true);
            Log("Server stoping");
            cancellation.Cancel();
            Console.ReadKey(true);
        }
Example #26
0
        public Form1()
            : base("Snap N Viewer", 20, 20, 640, 480)
        {
            fAutoScale = true;

            // Create the backing buffer to retain the image
            fBackingBuffer = new GDIDIBSection(1600, 1200);

            // 1.  Show a dialog box to allow the user to type in the 
            // group IP address and port number.
            HostForm groupForm = new HostForm();
            //groupForm.ShowDialog();

            // 2. Get the address and port from the form, and use
            // them to setup the MultiSession object
            string groupIP = groupForm.groupAddressField.Text;
            int groupPort = int.Parse(groupForm.groupPortField.Text);
            IPEndPoint ipep = new IPEndPoint(IPAddress.Parse(groupIP), groupPort);

            Title = "Snap N Viewer - " + ipep.ToString();

            fCommChannel = new CommChannel(ipep, false, true);

            // 3. Setup the chunk decoder so we can receive new images
            // when they come in
            fChunkDecoder = new GraphPortChunkDecoder(fBackingBuffer, fCommChannel);
            fChunkDecoder.PixBltPixelBuffer24Handler += this.PixBltPixelBuffer24;
            fChunkDecoder.PixBltLumbHandler += this.PixBltLum24;
        }
Example #27
0
        Packet CheckLogin(Proxy.ClientSession sess, Packet p, IPEndPoint ip)
        {
            string IP = ip.ToString();
            if (BannedIPs.Contains(IP))
                sess.InjectPacket(new DisconnectPacket() {Message="You are banned from this server."});

            return p;
        }
        private void HandleIncomingMessages(byte[] data, System.Net.IPEndPoint endpoint)
        {
            __logger.Debug("Received from {0}:{1}", endpoint.ToString(),
                           string.Join(",", (from a in data select a.ToString("X2")).ToArray()));

            if (PacketReceived != null)
            {
                var split = endpoint.ToString().Split(':');

                var packet = ParseBytesToLIFXProtocolPacket(data);
                PacketReceived(this, new PacketReceivedEventArgs()
                {
                    Packet        = packet,
                    RemoteAddress = split[0]
                });
            }
        }
        public F命令列表窗口(IPEndPoint __地址, string __名称 = "")
        {
            InitializeComponent();

            __名称 = string.IsNullOrEmpty(__名称) ? __地址.ToString() : __名称;
            this.f命令列表1.地址 = __地址;
            this.f命令列表1.名称 = __名称;
        }
Example #30
0
    // Connected to server
    void uLink_OnConnectedToServer(System.Net.IPEndPoint nServer)
    {
        LogManager.General.Log("Successfully connected to server: " + nServer.ToString());

        disconnected = false;
        server       = nServer;

        Screen.showCursor = false;
    }
 /// <summary>
 /// Logs specified send.
 /// </summary>
 /// <param name="data">Data what was sent.</param>
 /// <param name="localEndPoint">Local IP end point.</param>
 /// <param name="remoteEndPoint">Remote IP end point.</param>
 public void AddSend(byte[] data,IPEndPoint localEndPoint,IPEndPoint remoteEndPoint)
 {
     try{
         string text = "Sending (" + data.Length + " bytes): " + localEndPoint.ToString() + " -> " + remoteEndPoint.ToString() + "\r\n<begin>\r\n" + System.Text.Encoding.UTF8.GetString(data) + "<end>\r\n";
         //System.IO.File.AppendAllText("c:\\sipx.txt",text);
     }
     catch{
     }
 }
Example #32
0
 private bool CheckNatMessage(byte[] data, IPEndPoint endpoint)
 {
     if (((data.Length > 4) && (data[0] == 8)) && ((data[1] == 0) && (data[2] == 0)))
     {
         EventLog.WriteLine("Got a nat message from: " + endpoint.ToString(), new object[0]);
         return true;
     }
     return false;
 }
 public void Connect(IPEndPoint target)
 {
     _serverEndPoint = target;
     bool connected = _photon.Connect(target.ToString(), _applicationName);
     if(!connected)
         throw new Exception("Photon Client can't connect to " + target);
     //if(connected)
     //    _channelListener = _channelFactory.OnNetConnect(this);
 }
        static void Main(string[] args)
        {
            if (PerformanceCounters.CreatePerformanceCounters())
                return;

            // reseting peformance counter
            PerformanceCounters.Connected.RawValue = 0;

            // configuring logging
            log4net.Config.XmlConfigurator.Configure();
            _log.Info("Starting Echo Server");
            AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException;

            // opening TLS certificate
            X509Store store = new X509Store(StoreName.My, StoreLocation.LocalMachine);
            store.Open(OpenFlags.ReadOnly);
            store.Certificates.Count.ToString();
            var certificate = store.Certificates[1];
            store.Close();
            
            CancellationTokenSource cancellation = new CancellationTokenSource();
            
            // local endpoint
            var endpoint = new IPEndPoint(IPAddress.Any, 8006);
            
            // starting the server
            WebSocketListener server = new WebSocketListener(endpoint, new WebSocketListenerOptions() 
            {
                SubProtocols = new []{"text"},
                PingTimeout = TimeSpan.FromSeconds(5),
                NegotiationTimeout = TimeSpan.FromSeconds(5),
                ParallelNegotiations = 16,
                NegotiationQueueCapacity = 256,
                TcpBacklog = 1000,
                BufferManager = BufferManager.CreateBufferManager((8192 + 1024)*1000, 8192 + 1024)
            });
            var rfc6455 = new vtortola.WebSockets.Rfc6455.WebSocketFactoryRfc6455(server);
            // adding the deflate extension
            rfc6455.MessageExtensions.RegisterExtension(new WebSocketDeflateExtension());
            server.Standards.RegisterStandard(rfc6455);
            // adding the WSS extension
            server.ConnectionExtensions.RegisterExtension(new WebSocketSecureConnectionExtension(certificate));

            server.Start();

            Log("Echo Server started at " + endpoint.ToString());

            var acceptingTask = Task.Run(()=> AcceptWebSocketClients(server, cancellation.Token));

            Console.ReadKey(true);
            Log("Server stoping");

            cancellation.Cancel();
            acceptingTask.Wait();

            Console.ReadKey(true);
        }
Example #35
0
 void tcpServerEngine_ClientDisconnected(System.Net.IPEndPoint ipe)
 {
     if (this.CheckAccess())
     {
         textBox_Log.AppendText(DateTime.Now.ToString("hh:mm:ss") + "\t" + ipe.ToString() + "\t离线\n");
     }
     else
     {
         this.Dispatcher.BeginInvoke(new CbDelegate <System.Net.IPEndPoint>(this.tcpServerEngine_ClientDisconnected), ipe);
     }
 }
Example #36
0
        private void baseListen()
        {
            bool flag = true;

            while (this.isListening)
            {
                byte[] array = new byte[63488];
                System.Net.EndPoint endPoint = null;
                try
                {
                    endPoint          = new System.Net.IPEndPoint(this.ipAddress, this.port);
                    this.serverSocket = new System.Net.Sockets.Socket(System.Net.Sockets.AddressFamily.InterNetwork, System.Net.Sockets.SocketType.Dgram, System.Net.Sockets.ProtocolType.Udp);
                    this.serverSocket.Bind(endPoint);
                    if (flag)
                    {
                        DebugCenter.GetInstance().clearStatusCode(DebugCenter.ST_TrapPortNA, true);
                        flag = false;
                    }
                    this.serverSocket.SetSocketOption(System.Net.Sockets.SocketOptionLevel.Socket, System.Net.Sockets.SocketOptionName.ReceiveTimeout, 0);
                    int num = this.serverSocket.ReceiveFrom(array, System.Net.Sockets.SocketFlags.None, ref endPoint);
                    if (num > 0 && this.isListening)
                    {
                        string[] separator = new string[]
                        {
                            ":"
                        };
                        string[]       array2         = endPoint.ToString().Split(separator, System.StringSplitOptions.None);
                        SocketMessager socketMessager = new SocketMessager();
                        socketMessager.Target    = array2[0];
                        socketMessager.Port      = System.Convert.ToInt32(array2[1]);
                        socketMessager.DataLenth = num;
                        socketMessager.DataBytes = array;
                        System.Threading.ThreadPool.QueueUserWorkItem(new System.Threading.WaitCallback(this.waitCallback), socketMessager);
                    }
                }
                catch (System.Exception)
                {
                    try
                    {
                        System.Threading.Thread.Sleep(100);
                    }
                    catch (System.Exception)
                    {
                    }
                }
                finally
                {
                    if (this.serverSocket != null)
                    {
                        this.serverSocket.Close();
                    }
                }
            }
        }
Example #37
0
    void test_ipendpoint_endpoint_equal()
    {
        System.Net.IPEndPoint ipep = new System.Net.IPEndPoint(System.Net.IPAddress.Parse("127.0.0.1"), 1912);
        System.Net.EndPoint   ep   = (System.Net.IPEndPoint)ipep;
        print(ipep.ToString());
        print(ep.ToString());
        print(ipep.Equals(ep));

        //System.Net.IPEndPoint ipep2 = new System.Net.IPEndPoint(System.Net.IPAddress.Any, 0);
        //System.Net.EndPoint sender = (System.Net.EndPoint)ipep;
        //sender = new
    }
Example #38
0
 private string GetLocalEndPoint(System.Net.Sockets.Socket s)
 {
     System.Net.NetworkInformation.IPGlobalProperties         iPGlobalProperties   = System.Net.NetworkInformation.IPGlobalProperties.GetIPGlobalProperties();
     System.Net.NetworkInformation.TcpConnectionInformation[] activeTcpConnections = iPGlobalProperties.GetActiveTcpConnections();
     System.Net.IPEndPoint iPEndPoint = (System.Net.IPEndPoint)s.RemoteEndPoint;
     System.Net.NetworkInformation.TcpConnectionInformation[] array = activeTcpConnections;
     for (int i = 0; i < array.Length; i++)
     {
         System.Net.NetworkInformation.TcpConnectionInformation tcpConnectionInformation = array[i];
         if (iPEndPoint.ToString() == tcpConnectionInformation.RemoteEndPoint.ToString())
         {
             return(new System.Net.IPEndPoint(tcpConnectionInformation.LocalEndPoint.Address, ((System.Net.IPEndPoint)s.LocalEndPoint).Port).ToString());
         }
     }
     return("127.0.0.1:0");
 }
Example #39
0
    public void Connect(ref System.Net.IPEndPoint addr)
    {
        //print("client connecting to %hhu.%hhu.%hhu.%hhu:%d\n",
        //        addr.GetA(), addr.GetB(), addr.GetC(), addr.GetD(), addr.GetPort());
        bool connected = IsConnected();

        ClearData();
        if (connected)
        {
            OnDisconnect();
        }
        mode    = Mode.Client;
        state   = State.Connecting;
        address = addr;
        Debug.Log("(0)address = " + address.ToString());
    }
Example #40
0
    public virtual bool SendPacket(byte[] data, int size)
    {
        //if (address.GetAddress() == 0)
        //{
        //    return false;
        //}
        byte[] packet = new byte[size + 4];
        packet[0] = (byte)(protocolID >> 24);
        packet[1] = (byte)((protocolID >> 16) & 0xff);
        packet[2] = (byte)((protocolID >> 8) & 0xff);
        packet[3] = (byte)(protocolID & 0xff);
        System.Buffer.BlockCopy(data, 0, packet, 4, data.Length);
        Debug.Log(ByteArrayToString(packet));

        Debug.Log("IP = " + address.ToString());
        return(socket.Send(ref address, packet, size + 4));
    }
Example #41
0
        private IEnumerable <Model.DnsObject> ExtractDnsObjects(System.Net.IPEndPoint client, System.Net.IPEndPoint server, string flowId, IEnumerable <FrameData> packetList)
        {
            var result = new List <DnsObject>();

            foreach (var frame in packetList)
            {
                try
                {
                    var packet       = Packet.ParsePacket((LinkLayers)frame.LinkLayer, frame.Data);
                    var udpPacket    = packet.Extract(typeof(UdpPacket)) as UdpPacket;
                    var stream       = new KaitaiStream(udpPacket.PayloadData);
                    var dnsPacket    = new DnsPacket(stream);
                    var clientString = client.ToString();
                    var serverString = server.ToString();
                    foreach (var(answer, index) in dnsPacket.Answers.Select((x, i) => (x, i + 1)))
                    {
                        var dnsObject = new Model.DnsObject
                        {
                            Client        = clientString,
                            Server        = serverString,
                            Timestamp     = frame.Timestamp,
                            FlowUid       = flowId,
                            TransactionId = $"{dnsPacket.TransactionId.ToString("X4")}-{index.ToString("D4")}",
                            DnsType       = answer.Type.ToString().ToUpperInvariant(),
                            DnsTtl        = answer.Ttl,
                            DnsQuery      = answer.Name.DomainNameString,
                            DnsAnswer     = answer.AnswerString,
                        };
                        result.Add(dnsObject);
                    }
                }
                catch (Exception e)
                {
                    m_ignite.Logger.Log(Apache.Ignite.Core.Log.LogLevel.Error, "ExtractDnsObjects error", null, null, "Error", "", e);
                }
            }
            return(result);
        }
Example #42
0
 private static void Client_Connected(object sender, System.Net.IPEndPoint e)
 {
     Console.WriteLine("Connected to {0}", e.ToString());
 }
Example #43
0
        protected override UdpFrame OnReceivedFrameData(byte[] data, System.Net.IPEndPoint ep)
        {
            if (data == null || data.Length < UdpFrame.HeadLength)
            {
                return(null);
            }

            UdpFrame frame = new UdpFrame(data);

            if (frame.Command == UdpCommand.Connect)
            {
                RemoveCachePackage(ep);
                ILogger l = LoggerManager.GetLogger(ep.Address.ToString() + "_" + ep.Port);
                l.Trace("收到连接命令:{0}", ep.ToString());
                //Logger.Trace("收到连接命令:{0}", ep.ToString());

                //连接成功
                UdpServerSession session = null;
                bool             isNew   = false;
                lock (clientList)
                {
                    session = clientList.FirstOrDefault(x => x.Target.Host == ep.Address.ToString() && ep.Port == x.Target.Port && x.ProxyID == frame.ProxyID);
                    if (session == null)
                    {
                        session = SessionFactory.CreateSession(null, new DnsEndPoint(ep.Address.ToString(), ep.Port)) as UdpServerSession;
                        // session = new UdpServerSession();
                        session.StartTime = DateTime.Now;
                        session.ProxyID   = frame.ProxyID;
                        //session.Target = new DnsEndPoint(ep.Address.ToString(), ep.Port);
                        session.Client     = new UdpServerSocketProxy(this, Client, session);
                        session.StartTime  = DateTime.Now;
                        session.ActiveTime = DateTime.Now;

                        clientList.Add(session);
                        isNew = true;
                        l.Trace("添加会话");
                    }
                    else
                    {
                        session.Client             = null;
                        session.ProxyID            = frame.ProxyID;
                        session.Target             = new DnsEndPoint(ep.Address.ToString(), ep.Port);
                        session.Client             = new UdpServerSocketProxy(this, Client, session);
                        session.Client.IsConnected = true;
                        l.Trace("更新会话");
                    }
                    if (isNew)
                    {
                        OnClientConnected(session);
                    }
                }
                UdpFrame ccFrame = new UdpFrame(0, 0, 0, UdpCommand.ConnectConfirm, null, frame.ProxyID);
                SendFrame(ccFrame, session.Target);
                return(null);
            }
            else if (frame.Command == UdpCommand.Close)
            {
                ILogger          l       = LoggerManager.GetLogger(ep.Address.ToString() + "_" + ep.Port);
                UdpServerSession session = getSession(ep.Address.ToString(), ep.Port, frame.ProxyID);
                if (session != null)
                {
                    session.Client.IsConnected = false;
                    l.Trace("收到回话关闭命令:{0}", session.Target);
                    RemoveSession(session);
                }
            }
            else if (frame.Command == UdpCommand.Pong)
            {
                List <UdpServerSession> sl = null;
                lock (clientList)
                {
                    sl = clientList.Where(x => x.Target.Host == ep.Address.ToString() && x.Target.Port == ep.Port).ToList();
                }
                sl.ForEach(s =>
                {
                    s.ActiveTime      = DateTime.Now;
                    s.LastReceiveTime = DateTime.Now;
                });
                //UdpServerSession session = getSession(ep.Address.ToString(), ep.Port, frame.ProxyID);
                //if (session != null)
                //{
                //    session.ActiveTime = DateTime.Now;
                //    session.LastReceiveTime = DateTime.Now;
                //}
            }
            else if (frame.Command == UdpCommand.Ping)
            {
                //UdpServerSession session = getSession(ep.Address.ToString(), ep.Port, frame.ProxyID);
                //if (session != null)
                //{
                //    Logger.Trace("收到Ping命令:{0}", session.Target);
                //    UdpFrame pong = new UdpFrame(0, 0, 0, UdpCommand.Pong, null, frame.ProxyID);
                //    SendFrame(pong, ep);

                //}

                UdpFrame pong = new UdpFrame(0, 0, 0, UdpCommand.Pong, null, frame.ProxyID);
                SendFrame(pong, ep);

                List <UdpServerSession> sl = null;
                lock (clientList)
                {
                    sl = clientList.Where(x => x.Target.Host == ep.Address.ToString() && x.Target.Port == ep.Port).ToList();
                }
                sl.ForEach(s =>
                {
                    s.ActiveTime      = DateTime.Now;
                    s.LastReceiveTime = DateTime.Now;
                });
            }


            return(frame);
        }
Example #44
0
        private void ShowEvent(string msg, System.Net.IPEndPoint ipe)
        {
            var curResult = AppInfo.ClientInfoList.Where(p => p.IP == ipe.Address.ToString());

            if (curResult == null || curResult.FirstOrDefault() == null)
            {
                return;
            }
            if (this.InvokeRequired)
            {
                this.BeginInvoke(new CbDelegate <string, System.Net.IPEndPoint>(this.ShowEvent), msg, ipe);
            }
            else
            {
                if (msg == "上线")
                {
                    #region  线处理

                    var result = SystemInfo.ClientInfoList.Where(p => p.Ip == ipe.Address.ToString());
                    if (result == null || result.FirstOrDefault() == null)
                    {
                        ShowMsghomeControl("设备" + ipe.Address.ToString() + "上线");
                        ClientInfo info = new ClientInfo();
                        info.IpPoint  = ipe;
                        info.StateDes = "在线";
                        info.IsOnLine = 1;
                        if (curResult != null)
                        {
                            info.Code = curResult.FirstOrDefault().Code;
                            info.Name = curResult.FirstOrDefault().Name;
                        }
                        info.Ip     = ipe.Address.ToString();
                        info.FctPos = SystemInfo.FctPosList.Where(p => p.IP == ipe.Address.ToString()).FirstOrDefault();
                        SystemInfo.ClientInfoList.Add(info);
                    }
                    else
                    {
                        ShowMsghomeControl("设备" + ipe.Address.ToString() + "上线....");
                        result.FirstOrDefault().IsOnLine = 1;
                        result.FirstOrDefault().IpPoint  = ipe;
                        result.FirstOrDefault().StateDes = "在线";
                        result.FirstOrDefault().Ip       = ipe.Address.ToString();
                        result.FirstOrDefault().FctPos   = SystemInfo.FctPosList.Where(p => p.IP == ipe.Address.ToString()).FirstOrDefault();
                    }

                    #endregion
                }
                if (msg == "下线")
                {
                    #region  线处理

                    ShowMsghomeControl("设备" + ipe.Address.ToString() + "下线....");
                    var result = SystemInfo.ClientInfoList.Where(p => p.Ip == ipe.Address.ToString());
                    if (result != null && result.FirstOrDefault() != null)
                    {
                        result.FirstOrDefault().State    = 0;
                        result.FirstOrDefault().StateDes = "下线";
                        result.FirstOrDefault().IsOnLine = 0;
                        result.FirstOrDefault().IpPoint  = ipe;
                    }
                    #endregion
                }
                this.toolStripLabel_event.Text = ipe.ToString() + msg;
            }
        }
Example #45
0
        //Connect to the data source on the given socket
        public bool Connect(string server_hostname, int server_port)
        {
            hostname = server_hostname;

            //[Concern("Logging")]

            /*MyTrace.Log(TraceLevel.Info, "Connecting to {0}:{1}",
             *      server_hostname, server_port);*/

            //[Concern("EH")]
            try
            {
                udp = new MyUdpClient(server_hostname, server_port);

                IPHostEntry host = Dns.GetHostEntry(server_hostname);
                //[Concern("EC")]
                if (host.AddressList.Length <= 0)
                {
                    //[Concern("Logging")]

                    /*MyTrace.Log(TraceLevel.Warning,
                     *      "Could not find IP address of server '{0}'.",
                     *      server_hostname);*/
                    Close();
                    return(false);
                }

                sourcePoint = new System.Net.IPEndPoint(host.AddressList[0], server_port);
                //[Concern("Logging")]
                Log.Write("SourcePoint: " + sourcePoint.ToString());

                // NOTE: We should send a test message here so that we know right away if
                // ISenseServer is running (reduces delay).

                return(true);
            }
            catch (SocketException ex)
            {
                // The help docs say that ex.ErrorCode will be the socket error code
                // but its wrong. The value should be WSAECONNRESET but instead its E_FAIL.
                //[Concern("Logging")]
                if (ex.Message.IndexOf("forcibly") > -1)
                {
                    // ISenseServer died (CTRL^C)

                    /*MyTrace.Log(TraceLevel.Warning,
                     *      "InterSenseSocket::Connect() - ISenseServer '{0}' appears to have died.",
                     *      server_hostname);*/
                }
                else
                {
                    /*MyTrace.Log(TraceLevel.Info, "InterSenseSocket::Connect() - Error creating udp Connection to {0}:{1} : {2}",
                     *      server_hostname,
                     *      server_port,
                     *      ex.ToString());*/
                }

                Close();
                return(false);
            }
            catch (Exception)
            {
                //[Concern("Logging")]

                /*MyTrace.Log(TraceLevel.Info, "InterSenseSocket::Connect() - Error creating udp Connection to {0}:{1} : {2}",
                 *      server_hostname,
                 *      server_port,
                 *      ex.ToString());*/
                Close();
                return(false);
            }
        }
Example #46
0
 private void ClientInstance_Connected(object sender, System.Net.IPEndPoint e)
 {
     ISLogger.Write("Connected to server");
     ConfigFile.TryWriteProperty(ServiceConfigProperties.LastConnectedAddress, e.ToString());
 }