Stop() public method

public Stop ( ) : void
return void
示例#1
1
        public void NoChannelForkGroup()
        {
            using (ShortcutTestClass shortcutTestClass = ParallelizationFactory.GetParallelized<ShortcutTestClass>())
            {
                TcpListener tcpListener = new TcpListener(IPAddress.Loopback, 23000);
                tcpListener.Start();

                shortcutTestClass.NoChannelForkGroup("Test");

                int i = 0;
                while (!tcpListener.Pending())
                {
                    Thread.Sleep(100);
                    if (i++ > 20)
                    {
                        tcpListener.Stop();
                        throw new TimeoutException();
                    }
                }

                TcpClient tcpClient = tcpListener.AcceptTcpClient();
                Expect(new StreamReader(tcpClient.GetStream()).ReadToEnd(), EqualTo("Test"));

                tcpClient.Close();
                tcpListener.Stop();
            }
        }
        public static IDisposable HandleClients(TcpListener listener, Func<TcpClient, string, Task> handleClientAccessPolicy, string policyResponse)
        {
            listener.Start();

            var disposableHandler = ThreadPoolScheduler.Instance.ScheduleAsync(async (scheduler, ct) =>
            {
                var disposable = new BooleanDisposable();

                while (!disposable.IsDisposed)
                {
                    var client = await listener.AcceptTcpClientAsync();
                    await handleClientAccessPolicy(client, policyResponse);
                    await scheduler.Yield();
                }

                return disposable;
            });

            var compositeDisposable = new CompositeDisposable();

            compositeDisposable.Add(Disposable.Create(() => listener.Stop()));
            compositeDisposable.Add(disposableHandler);

            return compositeDisposable;
        }
示例#3
0
文件: Worker.cs 项目: Zhangerr/pulse
        public void start(object port)
        {
            listener = new TcpListener((int)port);
            listener.Start();
            try
            {
                while (true)
                {

                    if (Form1.stop)
                    {
                        Console.WriteLine("broke");
                        listener.Stop();
                        break;
                    }
                    TcpClient client = listener.AcceptTcpClient();
                    ClientHandler ch = new ClientHandler(client);
                    Form1.clients.Add(ch);
                    Form1.form.Invoke(new Form1.changeText(Form1.form.changeLabel), "Connected:" + Form1.clients.Count);
                    ch.clientDC += Form1.clientDCed;
                    Thread t = new Thread(new ThreadStart(ch.start));
                    t.Start();

                }
            }
            catch (ThreadAbortException t)
            {
                //this shit isn't called because of the block of accepting tcp
                Console.WriteLine("got the abort");
                listener.Stop();
            }
        }
示例#4
0
        public void MassiveInvoke()
        {
            using (ChordTestClass chordTestClass = ParallelizationFactory.GetParallelized<ChordTestClass>())
            {
                List<TcpListener> tcpListeners = new List<TcpListener>();

                for (int i = 0; i < 500; i++)
                {
                    TcpListener tcpListener = new TcpListener(IPAddress.Loopback, 23000 + i);
                    tcpListeners.Add(tcpListener);
                    tcpListener.Start();
                    chordTestClass.TestMethod4(string.Format("V{0}", i));
                    chordTestClass.TestMethod5(i);
                }

                List<string> results = new List<string>();

                foreach (TcpListener tcpListener in tcpListeners)
                {
                    int i = 0;
                    var timeout = 10;
                    while (!tcpListener.Pending())
                    {
                        Thread.Sleep(100);
                        if (++i > timeout)
                        {
                            tcpListener.Stop();
                            throw new TimeoutException();
                        }
                    }

                    TcpClient tcpClient = tcpListener.AcceptTcpClient();
                    results.Add(new BinaryReader(tcpClient.GetStream()).ReadString());

                    tcpClient.Close();
                    tcpListener.Stop();
                }

                Debug.Print(string.Format("Received {0} results.", results.Count));

                List<string> results1 = new List<string>();
                List<string> results2 = new List<string>();

                foreach(string value in results)
                {
                    string[] values = value.Split(',');
                    results1.Add(values[0]);
                    results2.Add(values[1]);
                }

                for (int i = 0; i < 500; i++)
                {
                    Expect(results1.Contains(string.Format("V{0}", i)),
                           string.Format("Missing value1: {0}", i));
                    Expect(results2.Contains(string.Format("{0}", 23000 + i)),
                           string.Format("Missing value2: {0}", i));
                }

            }
        }
示例#5
0
        private void receivingWorker_DoWork(object sender, DoWorkEventArgs e)
        {
            while (client.Connected)
            {
                try
                {
                    // read from the buffer
                    stream = client.GetStream();
                    i      = stream.Read(readByte, 0, readByte.Length);
                    data   = Encoding.UTF8.GetString(readByte, 0, i);
                    this.txtReceive.Invoke(new MethodInvoker(delegate()
                    {
                        if (data != "['][CLOSE][']\r\n")
                        {
                            // propmt the received message from the buffer
                            txtReceive.AppendText("\nRECEIVED: " + data + "\n");
                        }
                    }));

                    if (data == "['][CLOSE][']\r\n")
                    {
                        // end connection if token acquired
                        break;
                    }
                }

                catch (Exception ex)
                {
                    MessageBox.Show(ex.ToString());
                }
            }

            // release the resources
            STR.Close();
            STW.Close();
            receivingWorker.CancelAsync();
            client.Close();
            server.Stop();

            // reset button states
            if (InvokeRequired)
            {
                this.stopBtn.Invoke(new MethodInvoker(delegate()
                {
                    stopBtn.Enabled = false;
                }));
                this.startBtn.Invoke(new MethodInvoker(delegate()
                {
                    startBtn.Enabled = true;
                }));
            }
        }
示例#6
0
        public void MassiveInvoke()
        {
            using (ForkTestClass forkTestClass = ParallelizationFactory.GetParallelized<ForkTestClass>())
            {
                List<TcpListener> tcpListeners = new List<TcpListener>();

                for (int i = 0; i < 500; i++)
                {
                    TcpListener tcpListener = new TcpListener(IPAddress.Loopback, 23000 + i);
                    tcpListeners.Add(tcpListener);
                    tcpListener.Start();

                    forkTestClass.MassiveTest(i.ToString());
                }

                List<int> results = new List<int>();

                foreach (TcpListener tcpListener in tcpListeners)
                {
                int i = 0;
                    var timeout = 10;
                    while (!tcpListener.Pending())
                    {
                        Thread.Sleep(100);
                        if (++i > timeout)
                        {
                            tcpListener.Stop();
                            throw new TimeoutException();
                        }
                    }

                    if(i > timeout)
                        continue;

                    TcpClient tcpClient = tcpListener.AcceptTcpClient();
                    results.Add(new BinaryReader(tcpClient.GetStream()).ReadInt32());

                    tcpClient.Close();
                    tcpListener.Stop();
                }

                Debug.Print(string.Format("Received {0} results.", results.Count));

                for (int i = 0; i < 500; i++)
                {
                    Expect(results.Contains(i), string.Format("Missing value: {0}", i));
                }

            }
        }
示例#7
0
        /// <summary>
        /// Initializes a new instance of the <see cref="file_server"/> class.
        /// Opretter en socket.
        /// Venter på en connect fra en klient.
        /// Modtager filnavn
        /// Finder filstørrelsen
        /// Kalder metoden sendFile
        /// Lukker socketen og programmet
        /// </summary>
        private file_server()
        {
            TcpListener serverSocket = new TcpListener(IPAddress.Parse("10.0.0.1"),PORT);

            TcpClient clientSocket = default(TcpClient);

            serverSocket.Start();

            Console.WriteLine("Server Started - Listening for client");

            clientSocket = serverSocket.AcceptTcpClient();

            Console.WriteLine("Client connected - Waiting for client to input filename");

            //Get filename

            NetworkStream networkStream = clientSocket.GetStream();

            string fileToSend = LIB.readTextTCP (networkStream);

            Console.WriteLine("Client trying to retrieve file: " + fileToSend + ". Finding file...");

            long fileLength = LIB.check_File_Exists (fileToSend);

            if (fileLength != 0) {
                Console.WriteLine ("Size of file " + fileLength);

                LIB.writeTextTCP (networkStream, "1");

                sendFile (fileToSend, fileLength, networkStream);

                //Close connection

                Console.WriteLine ("File sent - closing connection");

                clientSocket.Close ();

                serverSocket.Stop ();

                Console.WriteLine ("Exit");
            } else {
                LIB.writeTextTCP (networkStream, "0");
                Console.WriteLine ("404 - File not found");

                clientSocket.Close ();

                serverSocket.Stop ();
            }
        }
        public LoopbackTcpStream(params byte[] initialStagedReadBytes)
        {
            var tcpListener = new SystemTcpListener(IPAddress.Loopback, 0);

            try
            {
                tcpListener.Start();
                var clientSocket = new Socket(SocketType.Stream, ProtocolType.Tcp)
                {
                    NoDelay = true
                };
                clientSocket.Connect(tcpListener.LocalEndpoint);
                this._senderStream = new NetworkStream(clientSocket, true);
                var receiverSocket = tcpListener.AcceptSocket();
                this._receiverStream = new NetworkStream(receiverSocket, true);
                this.LocalEndPoint   = receiverSocket.LocalEndPoint;
                this.RemoteEndPoint  = receiverSocket.RemoteEndPoint;

                this._writtenBytes = new BufferBlock <byte>();
            }
            finally
            {
                tcpListener.Stop();
            }

            if (initialStagedReadBytes != null)
            {
                this.StageReadBytes(initialStagedReadBytes);
            }
        }
示例#9
0
        public int FindFreePort(int startingPort)
        {
            Exception lastException = null;

            for (int i = startingPort; i < 65535; i++)
            {
                try
                {
                    var listener = new TcpListener(IPAddress.Loopback, i);
                    listener.Start();
                    listener.Stop();

                    logger.Debug("Found free port: {0}", i);
                    return i;
                }
                catch (SocketException e)
                {
                    if (e.SocketErrorCode == SocketError.AddressAlreadyInUse)
                        lastException = e;
                    else
                        throw;
                }
            }

            throw lastException;
        }
示例#10
0
        public void ModbusTcpSlave_ConnectionClosesGracefully()
        {
            TcpListener slaveListener = new TcpListener(ModbusMasterFixture.TcpHost, ModbusMasterFixture.Port);
            slaveListener.Start();
            ModbusTcpSlave slave = ModbusTcpSlave.CreateTcp(ModbusMasterFixture.SlaveAddress, slaveListener);
            Thread slaveThread = new Thread(slave.Listen);
            slaveThread.IsBackground = true;
            slaveThread.Start();

            using (TcpClient masterClient = new TcpClient(ModbusMasterFixture.TcpHost.ToString(), ModbusMasterFixture.Port))
            {
                ModbusIpMaster master = ModbusIpMaster.CreateIp(masterClient);
                master.Transport.Retries = 0;

                bool[] coils = master.ReadCoils(1, 1);
                Assert.AreEqual(1, coils.Length);

                Assert.AreEqual(1, slave.Masters.Count);
            }

            // give the slave some time to remove the master
            Thread.Sleep(50);

            Assert.AreEqual(0, slave.Masters.Count);

            slaveListener.Stop();
        }
        public async Task ReadLineAsync_ThrowsOnConnectionClose()
        {
            TcpListener listener = new TcpListener(IPAddress.Loopback, 0);

            try
            {
                listener.Start();
                Task<TcpClient> acceptTask = listener.AcceptTcpClientAsync();

                TcpClient client = new TcpClient();
                await client.ConnectAsync(IPAddress.Loopback, ((IPEndPoint)listener.LocalEndpoint).Port);

                using (TcpClient serverTcpClient = await acceptTask)
                {
                    TcpClientConnectionChannel channel = new TcpClientConnectionChannel(serverTcpClient);
                    client.Dispose();

                    await Assert.ThrowsAsync<ConnectionUnexpectedlyClosedException>(async () =>
                    {
                        await channel.ReadLineAsync();
                    });
                }
            }
            finally
            {
                listener.Stop();
            }
        }
示例#12
0
            static private void ListenHandler()
            {
                var myIP        = Communication.GetLocalIP();
                var epLocal     = new System.Net.IPEndPoint(myIP, TCPPort);
                var tcpListener = new System.Net.Sockets.TcpListener(epLocal);

                tcpListener.Start();

                while (IsListening)
                {
                    System.Threading.Thread.Sleep(1000);
                    if (tcpListener.Pending())
                    {
                        var tcpClient = tcpListener.AcceptTcpClient();
                        var netStream = tcpClient.GetStream();
                        var buffer    = new byte[1024];
                        if (!netStream.DataAvailable)
                        {
                            continue;
                        }

                        List <byte> bufferTotal = new List <byte>();
                        while (netStream.DataAvailable)
                        {
                            netStream.Read(buffer, 0, 1024);
                            bufferTotal.AddRange(buffer);
                        }
                        tcpClient.Close();
                        netStream.Close();
                        var receive = System.Text.Encoding.UTF8.GetString(bufferTotal.ToArray());
                        Owner.Invoke(DgGetMsg, receive);
                    }
                }
                tcpListener.Stop();
            }
示例#13
0
 /// <summary>
 ///	Server's main loop implementation.
 /// </summary>
 /// <param name="log"> The Logger instance to be used.</param>
 public void Run( Logger log )
 {
     TcpListener srv = null;
     try
     {
         srv = new TcpListener( IPAddress.Loopback, portNumber );
         srv.Start();
         while ( true )
         {
             log.LogMessage( "Listener - Waiting for connection requests." );
             TcpClient socket = srv.AcceptTcpClient();
             socket.LingerState = new LingerOption( true, 10 );
             log.LogMessage( String.Format( "Listener - Connection established with {0}.",
                                                socket.Client.RemoteEndPoint ) );
                 // Instantiating protocol handler and associate it to the current TCP connection
              _dispatcher.ProcessConnection(socket.GetStream(), log);
              //Handler protocolHandler = new Handler( socket.GetStream(), log );
                 // Synchronously process requests made through de current TCP connection
                 //Task.Factory.StartNew((handler) => ((Handler) handler).Run(), protocolHandler);
                 //protocolHandler.Run();
             Program.ShowInfo( Store.Instance );
         }
     }
     finally
     {
         log.LogMessage( "Listener - Ending." );
         if ( srv != null )
         {
             srv.Stop();
         }
     }
 }
		void ReceiveTcpMethod(string[] args)
		{
			//Check for correct amount of arguments
			if (args.Length != 1)
				throw new ArgumentException("Parameters: <Port>");

			int port = Int32.Parse(args[0]);

			//Create a TcpListener to accept client connections
			TcpListener listener = new TcpListener(IPAddress.Any, port);
			listener.Start();

			TcpClient client = listener.AcceptTcpClient();

			//Receive text-encoded quote
			ItemQuoteDecoder decoder = new ItemQuoteDecoderText();
			ItemQuote quote = decoder.decode(client.GetStream());
			Console.WriteLine("Received text-encoded quote:");
			Console.WriteLine(quote);

			//Repeat quote with binary-encoding, adding 10 cents to the price
			ItemQuoteEncoder encoder = new ItemQuoteEncoderBin();
			quote.unitPrice += 10;
			Console.WriteLine("Sending (binary)...");
			byte[] bytesToSend = encoder.encode(quote);
			client.GetStream().Write(bytesToSend, 0, bytesToSend.Length);

			client.Close();
			listener.Stop();
		}
示例#15
0
 public void Dispose()
 {
     try {
         serverSocket.Stop();
     } catch (Exception ex) {
     }
 }
        public override void startListening()
        {
            while(!Stop) {
                try {
                    imageDelay = 1000;
                    listener = new TcpListener(this.GivenIPAddress, this.StartingPort);
                    listener.Start();
                    mainSocket = listener.AcceptSocket();
                    s = new NetworkStream(mainSocket);
                    while(true) {
                        Bitmap screeny = new Bitmap(InvokerForm.Width, InvokerForm.Height, PixelFormat.Format32bppArgb);
                        Graphics theShot = Graphics.FromImage(screeny);
                        theShot.ScaleTransform(.25F, .25F);
                        theShot.CopyFromScreen(InvokerForm.Left, InvokerForm.Top, 0, 0, InvokerForm.Size, CopyPixelOperation.SourceCopy);
                        BinaryFormatter bFormat = new BinaryFormatter();
                        bFormat.Serialize(s, screeny);

                        Thread.Sleep(imageDelay);
                        theShot.Dispose();
                        screeny.Dispose();
                    }
                }

                catch(Exception) {
                    if(mainSocket.IsBound)
                        mainSocket.Close();
                    if(listener != null)
                        listener.Stop();
                }
            }
        }
示例#17
0
		public void ProcessMessageTest()
		{
			// setup the client configurations
			TcpSendEndpoint sendEndpoint = new TcpSendEndpoint();
			TcpSendOptions options = new TcpSendOptions();
			options.Endpoint = new IPEndPoint(IPAddress.Loopback, 6789);
			sendEndpoint.Initialize(null, options);

			// start a tcp listener
			TcpListener listener = new TcpListener(new IPEndPoint(IPAddress.Any, 6789));
			listener.Start();

			// start the enpoint for processing
			sendEndpoint.StartProcessing();

			// send messages
			byte[] data = { 0x41, 0x41, 0x41, 0x41 };
			sendEndpoint.ProcessMessage(null, data); // AAAA

			// assert listener for receive of messages
			var socket = listener.AcceptSocket();
			byte[] readData = new byte[8];
			Assert.AreEqual(8, socket.Receive(readData, 0, 8, SocketFlags.None));

			// close the client
			sendEndpoint.StopProcessing();

			// close the server
			listener.Stop();

			// assert data is valid

			byte[] expectedData = { TcpSendOptions.SOH, TcpSendOptions.STX, 0x41, 0x41, 0x41, 0x41, TcpSendOptions.ETX, TcpSendOptions.EOT };
			Assert.IsTrue(expectedData.SequenceEqual(readData));
		}
示例#18
0
        public override Task StopAsync()
        {
            shutdownTokenSource.Cancel();
            listener.Stop();

            return(acceptTask);
        }
示例#19
0
 static void Main(string[] args)
 {
     bool done = false;
     //TcpListener listener = new TcpListener(portNum); //����VS2005 MSDN �˷����Ѿ���ʱ������ʹ��
     // IPEndPoint�� �������ʶΪIP��ַ�Ͷ˿ں�
     TcpListener listener = new TcpListener(new IPEndPoint(IPAddress.Any, portNum));
     listener.Start();
     while (!done)
     {
         Console.Write("Waiting for connection...");
         TcpClient client = listener.AcceptTcpClient();
         Console.WriteLine("Connection accepted.");
         NetworkStream ns = client.GetStream();
         byte[] byteTime = Encoding.ASCII.GetBytes(DateTime.Now.ToString());
         try
         {
             ns.Write(byteTime, 0, byteTime.Length);
             ns.Close();
             client.Close();
         }
         catch (Exception e)
         {
             Console.WriteLine(e.ToString());
         }
     }
     listener.Stop();
 }
示例#20
0
文件: Client.cs 项目: Jayancv/TankJC
        //to get messages from server
        public void recieve()
        {
            TcpListener listner = new TcpListener(IPAddress.Parse(ip), portOut);
            while (true)
            {
                listner.Start();
                TcpClient reciever = listner.AcceptTcpClient();
                Stream r_stream = reciever.GetStream();
                Byte[] bytes = new Byte[256];

                int i;
                data = null;

                while ((i = r_stream.Read(bytes, 0, bytes.Length)) != 0)
                {
                    data = System.Text.Encoding.ASCII.GetString(bytes, 0, i);
                }
                string[] lines = Regex.Split(data, ":");

                com.Invoke(new Action(() =>
                {
                        eval.evaluate(data, com);
                        com.displayData("\n msg => \n" + data + "\n");
                }));
                r_stream.Close();
                listner.Stop();
                reciever.Close();
            }
        }
示例#21
0
 public void StartThread()
 {
     Print("Server started");
     var listner=new TcpListener(IPAddress.Any, port);
     listner.Start();
     CvarcClient cvarcClient = null;
     while(true)
     {
         while (!listner.Pending())
         {
             if (exitRequest)
             {
                 if (cvarcClient != null)
                     cvarcClient.Close();
                 listner.Stop();
                 return;
             }
             Thread.Sleep(1);
         }
         var client = listner.AcceptTcpClient();
         Print("Client accepted");
         if (cvarcClient != null)
             cvarcClient.Close(); // этот метод должен внутри CvarcClient устанавливать флаг, при котором цикл внутри Read заканчивается исключением
         cvarcClient = new CvarcClient(client);
         if (ClientConnected != null)
             ClientConnected(cvarcClient);
     }
 }
示例#22
0
        public static void Main(string[] args)
        {
            IPAddress ip = IPAddress.Loopback;
            int port = 9000;

            byte[] buffer = new byte[256];

            TcpListener server = new TcpListener (ip, port);
            try {
                server.Start ();

                while (true) {
                    Console.WriteLine ("waiting for connection");
                    TcpClient client = server.AcceptTcpClient ();
                    Console.WriteLine ("connected " + client.Client.AddressFamily);

                    NetworkStream stream = client.GetStream ();

                    // receive data from client, send responses
                    int i;
                    while ((i = stream.Read (buffer, 0, buffer.Length)) != 0) {
                        HandleMessage (buffer, i);
                        SendResponse (stream, "response");
                    }
                }
            } catch (SocketException e) {
                Console.WriteLine ("SocketException: {0}", e);
            } finally {
                server.Stop ();
            }
        }
        public void Stop()
        {
            if (tcpListener != null)
            {
                if (tcpListener.Server.IsBound)
                {
                    if (connectedTcpClient != null)
                    {
                        if (connectedTcpClient.Client.IsBound)
                        {
                            connectedTcpClient.Client.Close();
                            connectedTcpClient = null;
                        }
                    }

                    source.Cancel();
                    tcpListener.Stop();

                    EventHandler serverStopedHandler = ServerStoped;
                    if (serverStopedHandler != null)
                    {
                        serverStopedHandler(this, null);
                    }
                }
            }
        }
示例#24
0
		public void GetAvailableTcpPortTest()
		{
			int Port = NetworkUtilities.GetAvailableTcpPort();
			var Listener = new TcpListener(IPAddress.Parse("127.0.0.1"), Port);
			Listener.Start();
			Listener.Stop();
		}
示例#25
0
        private static void StartServer()
        {
            Console.WriteLine("Starting SERVER...");

            var listener = new TcpListener(IPAddress.Any, ServerPort);
            var shouldTerminate = false;

            listener.Start();

            Console.WriteLine("Servidor iniciado. Aguardando nudes!!");

            do
            {
                using (var client = listener.AcceptTcpClient())
                {
                    var stream = client.GetStream();
                    var reader = new StreamReader(stream);
                    var receivedMessage = reader.ReadToEnd()?.Trim();

                    Console.WriteLine("Mensagem recebida: {0}", receivedMessage);

                    shouldTerminate = "exit".Equals(receivedMessage, StringComparison.OrdinalIgnoreCase);
                }
            }
            while (!shouldTerminate);

            listener.Stop();

            Console.WriteLine("Servidor finalizado");
        }
示例#26
0
        public void Start(Action<TcpClient, byte[]> onData, Action<TcpClient> onDisconnect)
        {
            TcpListener listener = new TcpListener(port);
            listener.Start();
            running = true;
            AutoResetEvent are = new AutoResetEvent(false);
            agent = new Agent<Action>(
                () => { },
                () => { },
                nextaction =>
                {

                    nextaction();

                    if (running)
                    {
                        return NextAction.WaitForNextMessage;
                    }
                    are.Set();
                    return NextAction.Finish;
                });

            agent.Start();

            agent.SendMessage(() => { StartAccepting(listener, onData, onDisconnect); });
            are.WaitOne();

            listener.Stop();
        }
示例#27
0
 // c:/wazaa/nimi.txt
 public static void ListenForFile(string pathAndFname)
 {
     TcpListener listener = new TcpListener(IPAddress.Any, 1095);
     listener.Start();
        Console.WriteLine("DLMGR: Listening....");
     while (true)
     {
         try
         {
             using (TcpClient incoming = listener.AcceptTcpClient())
             using (NetworkStream networkStream = incoming.GetStream())
             using (FileStream fileStream = File.OpenWrite(pathAndFname))
             {
                 networkStream.CopyTo(fileStream);
                 break; //järgmise faili jaoks
             }
         }
         catch (Exception)
         {
             Console.WriteLine("DLMGR: Error saving file");
             break;
         }
     }
     listener.Stop();
     Console.WriteLine("DLMGR: Download mngr stopped listening for incoming connections");
 }
示例#28
0
 public void StopTcpListener ()
 {
     var listener = new TcpListener (IPAddress.Loopback, 0);
     listener.Start ();
     listener.Stop ();
     Assert.Throws<InvalidOperationException> (() => listener.AcceptTcpClient ());
 }
示例#29
0
 public void FTP_Receive(string filename)
 {
     try
     {
         System.Net.IPAddress           localAdd = System.Net.IPAddress.Parse(ips.AddressList[0].ToString());
         System.Net.Sockets.TcpListener listener = new System.Net.Sockets.TcpListener(localAdd, FTPPORTNO);
         listener.Start();
         TcpClient     tcpClient = listener.AcceptTcpClient();
         NetworkStream nws       = tcpClient.GetStream();
         if (File.Exists("c:\\temp\\" + filename))
         {
             File.Delete("c:\\temp\\" + filename);
         }
         fs = new System.IO.FileStream("c:\\temp\\" + filename, FileMode.Append, FileAccess.Write);
         int counter    = 0;
         int totalBytes = 0;
         do
         {
             int bytesRead = nws.Read(data, 0, tcpClient.ReceiveBufferSize);
             totalBytes += bytesRead;
             fs.Write(data, 0, bytesRead);
             ToolStripStatusLabel1.Text = "Receiving " + totalBytes + " bytes....";
             Application.DoEvents();
             counter += 1;
         } while (!(!(nws.DataAvailable)));
         ToolStripStatusLabel1.Text = "Receiving " + totalBytes + " bytes....Done.";
         fs.Close();
         tcpClient.Close();
         listener.Stop();
     }
     catch (Exception ex)
     {
         MessageBox.Show(ex.ToString());
     }
 }
示例#30
0
        /// <summary>
        /// Pojedyńczy wątek serwera.
        /// </summary>
        public void start()
        {
            NpgsqlConnection conn = new NpgsqlConnection("Server=127.0.0.1;Port=5432;User Id=postgres;Password=przemek;Database=template1;");
            conn.Open();
            QueryMaker qm = new QueryMaker(conn);

            serverSocket = new TcpListener(ip, port);
            TcpClient clientSocket;

            serverSocket.Start();

            int counter = 0;

            while (true)
            {
                counter += 1;
                clientSocket = serverSocket.AcceptTcpClient();
                HandleClient client = new HandleClient(clientSocket, Convert.ToString(counter), qm);
                Thread thread = new Thread(new ThreadStart(client.getMessage));
                thread.Start();
            }
            //conn.Close();
            clientSocket.Close();
            serverSocket.Stop();

        }
示例#31
0
 public void Stop()
 {
     try
     {
         CTS.Cancel();
     }
     catch { }
     try { t1.Abort(); }
     catch { }
     try { t2.Abort(); }
     catch { }
     foreach (var a in clients)
     {
         try
         {
             a.Client.Close();
         }
         catch { }
     }
     try
     {
         tcpl.Stop();
     }
     catch { }
     System.Threading.Thread.Sleep(500);
 }
示例#32
0
        public void listen()
        {
            while (true)
            {
                portchanged = false;
                listener = new TcpListener(IPAddress.Any, Convert.ToInt32(settingsg.port));
                listener.Start();
                while (!portchanged)
                {
                    TcpClient s = listener.AcceptTcpClient();
                    lastip = ((IPEndPoint)s.Client.RemoteEndPoint).Address.ToString();
                    //if (lastip.StartsWith("127") || lastip.StartsWith("192.168"))
                    {
                        hpr p = new hpr(s, this);
                        new Thread(new ThreadStart(p.process)).Start();
                    }
                    //else
                    {
                        //s.Close();
                        //ff.append(String.Format("{1}- Rejected external client {0}", lastip, DateTime.Now));
                    }
                }

                listener.Stop();
            }
        }
示例#33
0
        static void Main(string[] args)
        {
            var settings = ConfigurationManager.AppSettings;
            var port = settings["COM_PORT"];
            var speed = Convert.ToInt32(settings["COM_SPEED"]);
            var tcpPort = Convert.ToInt32(settings["TCP_PORT"]);
            serial = new SerialManager(port, speed);
            Console.WriteLine("UART: " + port + " - " + speed);
            server = new HardwareTcpServer(tcpPort);
            server.OnServerState += server_OnServerState;
            server.OnClientState += server_OnClientState;
            server.OnData += server_OnData;
            serial.OnReceive += serial_OnReceive;
            serial.OnStateChange += serial_OnStateChange;
            serial.Connect();

           // bridge = new HttpToUartBridge(6200);

            TcpListener listener = new TcpListener(IPAddress.Parse("188.127.233.35"), tcpPort);
            listener.Start();
            Console.WriteLine("TCP: " + tcpPort);
            while (Thread.CurrentThread.ThreadState == ThreadState.Running)
            {
                Console.WriteLine("Listening " + tcpPort);
                while (!listener.Pending())
                {
                    Thread.Sleep(300);
                }
                server.AcceptTcpClient(listener.AcceptSocket());
            }
            Console.WriteLine("Stopped");
            listener.Stop();
            server.Close();
            serial.Close();
        }
示例#34
0
 /// <summary>
 ///  Thread for session with PythonServer
 /// </summary>
 private void Run()
 {
     try
     {
         // Build listener for python engine
         listener = new TcpListener(9669);
         listener.Start();
         //  Wait connection from python engine and if successful then create new socket to python engine
         pythonClient = listener.AcceptTcpClient();
         mainForm.PrintToLog(DateTime.Now.ToShortTimeString() + " :  Server trying start...", Color.Black);
         listener.Stop(); // stop listening because python engine connected to GUI
         flagRun = true;
         // Asynchronic StateObject
         StateObject stateObject = new StateObject();
         stateObject.workSocket = pythonClient.Client;
         // Begins to asynchronously receive data from a connected socket with  python engine
         pythonClient.Client.BeginReceive(stateObject.buffer, 0, StateObject.BufferSize, 0, new AsyncCallback(Read_Callback), stateObject);
     }
     catch (SocketException se)
     {
         mainForm.PrintToLog(se.Message, Color.Red);
     }
     catch (Exception e)
     {
         mainForm.PrintToLog(e.Message, Color.Red);
     }
 }
示例#35
0
        /// <summary>
        /// Stops this instance.
        /// </summary>
        public override void Stop()
        {
            if (_log.Enabled)
            {
                _log.Debug(GetHashCode(), "Stop");
            }

            try
            {
                if (_listenerThread != null)
                {
                    _listenerThread.Abort();
                }

                if (_tcpListener != null)
                {
                    _tcpListener.Stop();
                }

                _isRunning = false;
            }
            catch (Exception ex)
            {
                _log.Error(GetHashCode(), "Failed to stop the tcp listener.", ex);
            }
        }
        public void Listen()
        {
            TcpListener listener = new TcpListener(IPAddress.Any,
                Convert.ToInt32(ConfigurationManager.AppSettings["tcpPort"]));
            try
            {
                listener.Start();
                int clientNr = 0;
                OnLogged("Waiting for a connection...");
                while (continueProcess)
                {
                    if (listener.Pending())
                    {
                        TcpClient handler = listener.AcceptTcpClient();

                        if (handler != null)
                        {
                            OnLogged("Client #{0} accepted", ++clientNr);

                            ClientHandler client = new ClientHandler(handler);
                            client.Logged += Logged;
                            connectionPool.Enqueue(client);
                        }
                    }

                    Thread.Sleep(100);
                }
            }
            finally
            {
                listener.Stop();
            }
        }
        /// <summary>
        /// return the base URL with finding unused TCP port number.
        /// </summary>
        private static string GenerateBaseURL()
        {
            var portNumbers = getRandoms(8000, 8999);
            var fixedPortNumber = ConfigurationManager.AppSettings["shell:FixedPortNumber"];
            if (string.IsNullOrEmpty(fixedPortNumber) == false)
            {
                portNumbers = new[] { int.Parse(fixedPortNumber) }.Concat(portNumbers);
            }

            var port = portNumbers.First(p =>
            {
                var listener = new TcpListener(IPAddress.Loopback, p);
                try
                {
                    listener.Start();
                    return true;
                }
                catch (Exception) { }
                finally
                {
                    listener.Stop();
                }
                return false;
            });

            var baseURL = $"http://localhost:{port}/";
            return baseURL;
        }
        public void run()
        {
            IPAddress localAdd = IPAddress.Parse(StarryboundServer.config.proxyIP);
            TcpListener serversocket = new TcpListener(localAdd, StarryboundServer.config.proxyPort);

            serversocket.Start();
            StarryboundServer.logInfo("Proxy server has been started on " + localAdd.ToString() + ":" + StarryboundServer.config.proxyPort);
            StarryboundServer.serverState = ServerState.Running;

            try
            {
                while (true)
                {
                    TcpClient clientSocket = serversocket.AcceptTcpClient();
                    new Thread(new ThreadStart(new ClientThread(clientSocket).run)).Start();
                }
            }
            catch (Exception e)
            {
                StarryboundServer.logException("ListenerThread: " + e.ToString());
            }

            serversocket.Stop();
            StarryboundServer.logException("ListenerThread has failed - No new connections will be possible.");
            Console.ReadLine();
        }
示例#39
0
        /// <summary>
        /// Accept Connections
        /// </summary>
        /// <returns></returns>
        private async Task AcceptConnections()
        {
            listener = new TcpListener(Server.Address, Server.Port);
            var bufferSize = Buffer; // Get the current buffer size on start
            listener.Start();
            Running = true;

            // If there is an exception we want to output the message to the console for debugging
            try
            {
                // While the Running bool is true, the listener is not null and there is no cancellation requested
                while (Running && listener != null && !cancellationTokenSource.Token.IsCancellationRequested)
                {
                    var client = await listener.AcceptTcpClientAsync().WithWaitCancellation(cancellationTokenSource.Token);
                    if (client != null)
                    {
                        // Proxy the data from the client to the server until the end of stream filling the buffer.
                        await ProxyClientConnection(client, bufferSize);
                    }

                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }

            listener.Stop();
        }
        private void receivingWorker_DoWork(object sender, DoWorkEventArgs e)
        {
            while (client.Connected)
            {
                try
                {
                    data = STR.ReadLine();
                    this.txtReceive.Invoke(new MethodInvoker(delegate()
                    {
                        if (data != "['][CLOSE][']\r\n")
                        {
                            txtReceive.AppendText("\nRECEIVED: " + data + "\n");
                        }
                    }));

                    sendData();

                    if (data == "['][CLOSE][']\r\n")
                    {
                        break;
                    }
                }

                catch (Exception ex)
                {
                    MessageBox.Show(ex.ToString());
                }
            }

            STR.Close();
            STW.Close();
            receivingWorker.CancelAsync();
            client.Close();
            server.Stop();

            if (InvokeRequired)
            {
                this.stopBtn.Invoke(new MethodInvoker(delegate()
                {
                    stopBtn.Enabled = false;
                }));
                this.startBtn.Invoke(new MethodInvoker(delegate()
                {
                    startBtn.Enabled = true;
                }));
            }
        }
示例#41
0
 /*
  * @see Flash.Tools.Debugger.SessionManager#stopListening()
  */
 public override void stopListening()
 {
     if (m_serverSocket != null)
     {
         m_serverSocket.Stop();
         m_serverSocket = null;
     }
 }
示例#42
0
 public void Close()
 {
     try
     {
         _listener.Stop();
     }
     catch
     { }
 }
示例#43
0
        protected override void OnDisconnectStart()
        {
            /* 受付処理終了 */
            tcp_listener_.Stop();

            /* 全クライアントをシャットダウン */
            tcp_clients_.ForEach(client => client.Dispose());
            tcp_clients_.Clear();
        }
示例#44
0
 /// <summary>
 /// Stops listening for and disconnects all current connections
 /// </summary>
 public void Stop()
 {
     while (_clients.Count > 0)
         _clients[0].Socket.Disconnect();
     _listenProc?.Cancel();
     _listenProc?.Join(1000);
     _listenProc = null;
     _server?.Stop();
     IsListening = false;
 }
示例#45
0
 /// <summary>
 /// Stops listening for and disconnects all current connections
 /// </summary>
 public void Stop()
 {
     while (_clients.Count > 0)
     {
         _clients[0].DisconnectAsync().Wait();
     }
     _listenProc?.Cancel();
     _listenProc?.Join(1000);
     _listenProc = null;
     _server?.Stop();
     IsListening = false;
 }
 public void Stop()
 {
     _listener.Stop();
     if (_connector != null)
     {
         if (_connector.Connected)
         {
             _connector.Close();
         }
         _connector = null;
     }
 }
示例#47
0
        public void Start()
        {
            try
            {
                _serverListener.Start();
                var bytes = new byte[256];

                while (true)
                {
                    WriteLine("Waiting for a connection to port " + _port + "...");
                    TcpClient client;
                    try
                    {
                        client = _serverListener.AcceptTcpClient();
                    }
                    catch (Exception e)
                    {
                        WriteLine("Connection error " + e);
                        break;
                    }

                    WriteLine("Connected !");
                    var stream = client.GetStream();

                    int i;
                    while ((i = stream.Read(bytes, 0, bytes.Length)) != 0)
                    {
                        var data = Encoding.ASCII.GetString(bytes, 0, i);
                        WriteLine("Received: {0}", data);

                        data = data.ToUpper();

                        var msgBytes = Encoding.ASCII.GetBytes(data);

                        stream.Write(msgBytes, 0, msgBytes.Length);
                        WriteLine("Sent: {0}", data);
                    }

                    client.Close();
                }
            }
            catch (SocketException e)
            {
                WriteLine("SocketException : " + e);
            }
            finally
            {
                _serverListener.Stop();
            }

            Read();
        }
示例#48
0
 public void Dispose()
 {
     FeuerwehrCloud.Helper.Logger.WriteLine("|  *** Terminating FAX-Plugin");
     IsTerminating = true;
     try {
         TCL.Stop();
     } catch (Exception ex) {
     }
     try {
         ListenSockThread.Abort();
     } catch (Exception ex) {
     }
 }
示例#49
0
 /// <summary>
 /// 关闭端口连接
 /// </summary>
 public void Close()
 {
     if (thListen != null)
     {
         thListen.Abort();
     }
     thListen = null;
     if (tcp != null)
     {
         tcp.Server.Close();
         tcp.Stop();
     }
     tcp    = null;
     isOpen = false;
 }
示例#50
0
        /// <summary>
        /// Disposes the listener, releasing all resources and closing
        /// any active connections.
        /// </summary>
        public void Dispose()
        {
            if (disposed)
            {
                return;
            }

            disposed = true;
            listener.Stop();
            listener = null;
            listenerSubscription.Dispose();
            this.socketDisposable.Dispose();
            connections.ForEach(socket => socket.Dispose());
            observable.OnCompleted();
        }
示例#51
0
        // BCL Tcp Server
        public static async Task BclServer()
        {
            var listener = new System.Net.Sockets.TcpListener(Default.IPEndPoint);

            try {
                listener.Start();
                using (var client = await listener.AcceptTcpClientAsync()) {
                    var sr      = new StreamReader(client.GetStream());
                    var message = await sr.ReadToEndAsync();

                    Console.WriteLine("BCL: " + message);
                }
            } finally {
                listener.Stop();
            }
        }
        private void StartListening()
        {
            System.Net.Sockets.TcpListener server = null;

            try
            {
                server = new System.Net.Sockets.TcpListener(IPAddress.Parse(myIPAddress), Port);
                server.Start();
                TcpClient lastClient = null;
                while (true)
                {
                    AllDone.Reset();
                    if (Logger.Enabled)
                    {
                        Logger.Log("Ready for connection...");
                    }
                    var client = server.AcceptTcpClient();

                    if (client == lastClient)
                    {
                        Console.WriteLine("last client");
                    }

                    lastClient = client;

                    if (Logger.Enabled)
                    {
                        Logger.Log("Connected!");
                    }

                    Thread.Sleep(100);
                    new Thread(() => HandleMessage(client)).Start();
                }
            }
            catch (SocketException e)
            {
                if (Logger.Enabled)
                {
                    Logger.Log(string.Format("SocketException: {0}", e));
                }
            }
            finally
            {
                //Stop listening for new clients
                server.Stop();
            }
        }
        private void stopListener()
        {
            lock (_listenerLock)
            {
                if (_listener != null)
                {
                    _listener.Stop();
                    _listener.Server.Close();
                    if (_client != null)
                    {
                        _client.Close();
                    }

                    _listener = null;
                }
            }
        }
示例#54
0
 private void Run()
 {
     tcpListener.Start();
     running = true;
     Console.WriteLine("Server is running...");
     while (running)
     {
         Console.WriteLine("Waiting for connection...");
         TcpClient client = tcpListener.AcceptTcpClient();
         Console.WriteLine("client is connected.");
         Console.WriteLine();
         HandleClient(client);
         client.Close();
     }
     running = false;
     tcpListener.Stop();
 }
        private void MainForm_FormClosing(object sender, FormClosingEventArgs e)
        {
            if (ServerThread != null && ServerThread.IsAlive)
            {
                ns.Close();
                client.Close();
                listener.Stop();
                ServerThread.Abort();
                UnityProcess.Kill();
                UnityProcess.Close();
                UnityProcess.Dispose();
            }

            stop     = true;
            e.Cancel = Stop.Enabled;
            closing  = true;
        }
示例#56
0
        private void StartListening()
        {
            if (Logger.Enabled)
            {
                Logger.Log("Listening...");
            }

            System.Net.Sockets.TcpListener server = null;

            try
            {
                server = new System.Net.Sockets.TcpListener(IPAddress.Parse(myIPAddress), Port);
                server.Start();

                while (true)
                {
                    AllDone.Reset();
                    if (Logger.Enabled)
                    {
                        Logger.Log("waiting for connection...");
                    }

                    var client = server.AcceptTcpClient();

                    if (Logger.Enabled)
                    {
                        Logger.Log("connected");
                    }

                    new Thread(() => HandleMessage(client)).Start();
                }
            }
            catch (SocketException e)
            {
                if (Logger.Enabled)
                {
                    Logger.Log(string.Format("Socket Error : {0}", e));
                }
            }
            finally
            {
                //Stop listening for new clients
                server.Stop();
            }
        }
        public void Dispose()
        {
            IsActive = false;

            if (Listener != null)
            {
                Listener.Stop();
            }
            if (Thread.Count > 0)
            {
                Thread.Dispose();
            }
            if (Core.TcpClientCollection.Count > 0)
            {
                Core.TcpClientCollection.Dispose();
            }

            Core.Logger.Log("TcpListener Disposed.");
        }
示例#58
0
        public void StopNetwork()
        {
            if (!networkActive)
            {
                return;
            }

            networkActive = false;
            listener.Stop();

            foreach (Client peer in peers.Values)
            {
                packet_Bye(peer);
            }
            peers.Clear();
            peerCount      = 0;
            networkCaptain = null;
            Console.WriteLine("Network stopped");
        }
示例#59
0
        private void Form1_FormClosing(object sender, FormClosingEventArgs e)
        {
            AccurateTimer.Stop();
            if (inputThread != null && inputThread.IsAlive)
            {
                inputThread.Abort();
                SerialObj.Close();
            }

            if (ServerThread != null && ServerThread.IsAlive)
            {
                ns.Close();
                client.Close();
                listener.Stop();
                ServerThread.Abort();
                UnityProcess.Kill();
                UnityProcess.Close();
                UnityProcess.Dispose();
            }
        }
        /// <summary>
        /// Used to bind to a port then unbind to trigger any operating system firewall requests
        /// </summary>
        public static void PingForFirewall()
        {
            Task.Queue(() =>
            {
                try
                {
                    //IPAddress ipAddress = Dns.GetHostEntry(Dns.GetHostName()).AddressList[0];
                    //IPEndPoint ipLocalEndPoint = new IPEndPoint(ipAddress, 15937);
                    IPEndPoint ipLocalEndPoint = new IPEndPoint(IPAddress.Parse("127.0.0.1"), DEFAULT_PORT);

                    System.Net.Sockets.TcpListener t = new System.Net.Sockets.TcpListener(ipLocalEndPoint);
                    t.Start();
                    t.Stop();
                }
                catch (Exception ex)
                {
                    Logging.BMSLog.LogException(ex);
                }
            });
        }