public ServerContext(int port, int maxclients, ref List<string> TextStack, string OwnIP)
        {
            BeginSendUdpServerCallback = new AsyncCallback(OnBeginSendUdpServerCallbackFinished);
            ServerMessage = System.Text.Encoding.ASCII.GetBytes("OK:" + OwnIP);

            UdpServer = new UdpClient(new IPEndPoint(IPAddress.Any, 8011)); //da bei xp fehler

            UdpServer.JoinMulticastGroup(BroadcastServer.Address);

            UdpServer.BeginSend(ServerMessage, ServerMessage.Length, BroadcastServer, BeginSendUdpServerCallback, null);

            MaxClients = maxclients;

            Ip = IPAddress.Any;
            this.Port = port;

            listener = new TcpListener(Ip, Port);
            Clients = new List<ClientContext>(MaxClients);

            listener.Start();

            BeginAcceptSocketCallback = new AsyncCallback(OnClientConnected);

            this.TextStack = TextStack;
        }
Пример #2
1
        private void button2_Click(object sender, EventArgs e)
        {
            TcpListener serverSocket = new TcpListener(IPAddress.Any, 4955);
           
            TcpClient clientSocket = default(TcpClient);
            serverSocket.Start();
            
            clientSocket = serverSocket.AcceptTcpClient();
            

            try
            {
                
                NetworkStream networkStream = clientSocket.GetStream();
                byte[] bytesFrom = new byte[10025];
                networkStream.Read(bytesFrom, 0, (int)clientSocket.ReceiveBufferSize);
                string dataFromClient = System.Text.Encoding.ASCII.GetString(bytesFrom);
                dataFromClient = dataFromClient.Substring(0, dataFromClient.IndexOf("$"));
                MessageBox.Show( dataFromClient);
                
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.ToString());
            }
        }
Пример #3
1
 //Connect to the client
 public void connect()
 {
     if (!clientConnected)
     {
         IPAddress ipAddress = IPAddress.Any;
         TcpListener listener = new TcpListener(ipAddress, portSend);
         listener.Start();
         Console.WriteLine("Server is running");
         Console.WriteLine("Listening on port " + portSend);
         Console.WriteLine("Waiting for connections...");
         while (!clientConnected)
         {
             s = listener.AcceptSocket();
             s.SendBufferSize = 256000;
             Console.WriteLine("Connection accepted from " + s.RemoteEndPoint);
             byte[] b = new byte[65535];
             int k = s.Receive(b);
             ASCIIEncoding enc = new ASCIIEncoding();
             Console.WriteLine("Received:" + enc.GetString(b, 0, k) + "..");
             //Ensure the client is who we want
             if (enc.GetString(b, 0, k) == "hello" || enc.GetString(b, 0, k) == "hellorcomplete")
             {
                 clientConnected = true;
                 Console.WriteLine(enc.GetString(b, 0, k));
             }
         }
     }
 }
Пример #4
1
        public void StartListening()
        {
            R = RowacCore.R;
            R.Log("[Listener] Starting TCP listener...");
            TcpListener listener = new TcpListener(IPAddress.Any, 28165);
            listener.Start();

            while (true)
            {
                try
                {
                    var client = listener.AcceptSocket();
            #if DEBUG
                    R.Log("[Listener] Connection accepted.");
            #endif

                    var childSocketThread = new Thread(() =>
                    {
                        byte[] data = new byte[1048576]; // for screenshots and tasklists
                        int size = 0;
                        while (client.Available != 0)
                            size += client.Receive(data, size, 256, SocketFlags.None); // TODO: increase reading rate from 256?
                        client.Close();

                        string request = Encoding.ASCII.GetString(data, 0, size);
            #if DEBUG
                        R.Log(string.Format("Received [{0}]: {1}", size, request));
            #endif
                        ParseRequest(request);
                    });
                    childSocketThread.Start();
                }
                catch (Exception ex) { R.LogEx("ListenerLoop", ex); }
            }
        }
Пример #5
0
        public TcpServer(IPAddress ip, ushort port)
        {
            if (ip == null)
                throw new NullReferenceException("ip is null");

            _listener = new TcpListener(ip, port);
        }
Пример #6
0
        public async Task Start(IPAddress iP, int port)
        {
            tcpListener = new TcpListener(iP, port);

            connectedTcpClient = null;
            source             = new CancellationTokenSource();
            token = source.Token;

            tcpListener.Start();

            EventHandler serverStartedHandler = ServerStarted;

            if (serverStartedHandler != null)
            {
                serverStartedHandler(this, null);
            }

            connectedTcpClient = await Task.Run(() => tcpListener.AcceptTcpClientAsync(), token);

            if (connectedTcpClient != null)
            {
                EventHandler clientConnectedHandler = ClientConnected;
                if (clientConnectedHandler != null)
                {
                    clientConnectedHandler(this, null);
                }

                var c = new Thread(() => ServerReceive());
                c.Start();
            }
        }
Пример #7
0
        //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();
            }
        }
Пример #8
0
        static void Main(string[] args)
        {
            //string ipString = "127.0.0.1";
            //System.Net.IPAddress ipAdd = System.Net.IPAddress.Parse(ipString);

            string host = "localhost";

            System.Net.IPAddress ipAdd =
                System.Net.Dns.GetHostEntry(host).AddressList[0];

            //Listenするポート番号
            int port = 2001;

            //TcpListenerオブジェクトを作成する
            System.Net.Sockets.TcpListener listener =
                new System.Net.Sockets.TcpListener(ipAdd, port);

            //Listenを開始する
            listener.Start();

            Console.WriteLine($"Debug server started. port:{port}");

            TaskContext tc = new TaskContext();

            while (true)
            {
                Console.WriteLine($"Waiting client");
                TcpClient client = listener.AcceptTcpClient();

                Console.WriteLine($"Client is connected");

                ClientTask ct = new ClientTask();
                ct.Start(tc, client);
            }
        }
Пример #9
0
        public void CreateTcpListener()
        {
            TcpClient     client = null;
            NetworkStream ns     = null;

            System.IO.StreamReader sr = null;
            try
            {
                listener = new System.Net.Sockets.TcpListener(ipEndPoint);
                listener.Start();
                while (true)
                {
                    client = listener.AcceptTcpClient();
                    ns     = client.GetStream();
                    sr     = new System.IO.StreamReader(ns);
                    while (client.Connected)
                    {
                        string data = sr.ReadLine();
                        if (data != null)
                        {
                            textBox1.AppendText(data + "\r\n");
                        }
                    }
                }
            }
            catch (Exception error)
            {
                MessageBox.Show(error.ToString());
            }
        }
Пример #10
0
        public async void ListenAsync(string ip, int port)
        {
            if (Listening)
            {
                throw new Exception("Listening");
            }
            Listening = true;

            server = new System.Net.Sockets.TcpListener(IPAddress.Parse(ip), port);
            server.Start();
            ListeningStarted(this, server);
            Env.Print($"listening: {server.LocalEndpoint.ToString()}");
            try
            {
                while (true)
                {
                    Env.Print("waiting for a connection");
                    var client = await server.AcceptTcpClientAsync();

                    Env.Print("one incoming tcp connection");

                    var session = new TcpClientSession(client);
                    NewSession.Invoke(this, session);
                    TcpClientAccepted?.Invoke(this, session);
                    session.Receive();
                }
            }
            catch (Exception ex)
            {
                Env.Print(ex.Message);
            }
        }
Пример #11
0
        /// <summary>
        /// Create an new Instance of the TCP-Listener on Port 5000
        /// </summary>
        internal Server()
        {
            try
            {
                AnrlDB.AnrlDataContext db = new AnrlDB.AnrlDataContext();
                if (!db.DatabaseExists())
                {
                    db.CreateDatabase();
                }

                CalculateTabels = new System.Timers.Timer(20000);
                CalculateTabels.Elapsed += new ElapsedEventHandler(CalculateTabels_Elapsed);
                CalculateTabels.Start();

                running = true;
                this.tcpListener = new TcpListener(IPAddress.Any, 5000);
                this.listenThread = new Thread(new ThreadStart(ListenForClients));
                this.listenThread.Start();
                db.Dispose();
            }
            catch (Exception ex)
            {
                Logger.Log("Exception in Server.Server" + ex.ToString(), 11);
            }
        }
Пример #12
0
        protected override EventResult OnConnectBusy()
        {
            var addr_family = (devp_.AddressFamily.Value == AddressFamilyType.IPv6) ? (AddressFamily.InterNetworkV6) : (AddressFamily.InterNetwork);

            try {
                /* ソケット生成 + バインド */
                switch (devp_.LocalBindMode.Value)
                {
                case BindModeType.INADDR_ANY:
                    local_ep_text_ = string.Format("INADDR_ANY:{0}", devp_.LocalPortNo.Value);
                    tcp_listener_  = new TcpListener((addr_family == AddressFamily.InterNetworkV6) ? (IPAddress.IPv6Any) : (IPAddress.Any), (ushort)devp_.LocalPortNo.Value);
                    break;

                case BindModeType.SelectAddress:
                    /* 選択中のアドレスファミリと異なる設定の場合はエラー */
                    if (devp_.LocalIpAddress.Value.AddressFamily != addr_family)
                    {
                        return(EventResult.Error);
                    }

                    local_ep_text_ = string.Format("{0}:{1}", devp_.LocalIpAddress.Value, devp_.LocalPortNo.Value);
                    tcp_listener_  = new TcpListener(devp_.LocalIpAddress.Value, (ushort)devp_.LocalPortNo.Value);
                    break;
                }

                /* 待ち受け開始 */
                tcp_listener_.Start((int)devp_.Capacity.Value);

                return(EventResult.Success);
            } catch {
                return(EventResult.Error);
            }
        }
Пример #13
0
        public void Start()
        {
            // 01 Listen to the endpoint
            this.listener = new System.Net.Sockets.TcpListener(this.endpoint);
            try
            {
                this.listener.Stop();
                this.listener.Start();
                this.isRunning = true;
            } catch (System.Net.Sockets.SocketException)
            {
                Console.WriteLine($"Server says: Can not listen local:'{this.endpoint.Port}'. Quit.");
                var errorMessage = new Message(99, $"Server can not listen local:'{this.endpoint.Port}'.");
                return;
            }

            Console.WriteLine();
            Console.WriteLine("------------------------------------------");
            Console.WriteLine($"Server started at '{System.DateTime.Now}'");
            Console.WriteLine("------------------------------------------");
            Console.WriteLine();

            // 02 (Loop)Receive the request and send response.
            while (this.IsRunning())
            {
                using (var stream = this.listener.AcceptTcpClient().GetStream())
                {
                    this.ReadProcessWrite(stream);
                }
            }
        }
Пример #14
0
        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);
            }
        }
Пример #15
0
        public async Task Start(string remoteServerIp, ushort remoteServerPort, ushort localPort, string localIp)
        {
            //var clients = new ConcurrentDictionary<IPEndPoint, TcpClient>();

            IPAddress localIpAddress = string.IsNullOrEmpty(localIp) ? IPAddress.IPv6Any : IPAddress.Parse(localIp);
            var       server         = new System.Net.Sockets.TcpListener(new IPEndPoint(localIpAddress, localPort));

            server.Server.SetSocketOption(SocketOptionLevel.IPv6, SocketOptionName.IPv6Only, false);
            server.Start();

            Console.WriteLine($"TCP proxy started {localPort} -> {remoteServerIp}|{remoteServerPort}");
            while (true)
            {
                try
                {
                    var remoteClient = await server.AcceptTcpClientAsync();

                    remoteClient.NoDelay = true;


                    new TcpClient(remoteClient, new IPEndPoint(IPAddress.Parse(remoteServerIp), remoteServerPort));
                }
                catch (Exception) { }
            }
        }
        public void clientServerInit()
        {
            try
            {
                // Start server
                this.tcpserver = new System.Net.Sockets.TcpListener(System.Net.IPAddress.Parse(this.networkConfig.ipAddress), this.networkConfig.port);
                this.tcpserver.Start();

                // Start thread to listening for new clients
                this.clientListenerThread = new System.Threading.Thread(new System.Threading.ThreadStart(clientListener));
                this.clientListenerThread.Start();

                // Start thread to listening on removed clients
                //this.clientRemoverThread = new System.Threading.Thread(new System.Threading.ThreadStart(clientRemover));
                // this.clientRemoverThread.Start();

                if (this.statusChangedEvent != null)
                {
                    this.statusChangedEvent(this.communicationName + ": Server started. Listening for Clients at Port - " + this.networkConfig.port);
                }
            }
            catch (System.Net.Sockets.SocketException ex)
            {
                Debug.Write("Error in clientServerInit: " + ex);
            }
        }
Пример #17
0
        private ServerCore()
        {
            LoadConfig();
            RegisterCommanders();
            try
            {
                sqlConnecter = SqlConnector.Instance;
            }
            catch (Exception ex)
            {
                Console.WriteLine("Could not connect to Mysql: \"" + ex.Message + "\"");
                Console.WriteLine("Aborting. Press any key to exit");
                Console.Read();
                return;
            }
            idConnection     = new Dictionary <UInt32, TcpClient>();
            connectionWorker = new Dictionary <TcpClient, ClientWorker>();
            connectionId     = new Dictionary <TcpClient, UInt32>();
            workers          = new List <ClientWorker>();
            TcpListener tcpListener = new System.Net.Sockets.TcpListener(IPAddress.Parse(ip), port);

            tcpListener.Start();
            while (true)
            {
                TcpClient connection = tcpListener.AcceptTcpClient();
                Console.WriteLine("Someone connected");
                ClientWorker worker = new ClientWorker(connection);
                lock (mutex)
                {
                    connectionWorker.Add(connection, worker);
                    workers.Add(worker);
                }
            }
        }
Пример #18
0
		public Form2(String hostPort, Form1 form1)
		{
			//
			// Required for Windows Form Designer support
			//
			InitializeComponent();

			//
			// TODO: Add any constructor code after InitializeComponent call
			//
			dataReadyToSend = new AutoResetEvent(false);
			refToForm1 = form1;
			// Resolve the local host.
			IPHostEntry localHost = Dns.Resolve(Dns.GetHostName());
			// Create a local end point for listening.
			IPEndPoint localEndPoint = new IPEndPoint(localHost.AddressList[0], 4001);
			// Instantiate the TCP Listener.
			tcpListener = new TcpListener(localEndPoint);
			tcpListener.Start();
			tcp = tcpListener.AcceptTcpClient();
			ethernetThreadStart = new ThreadStart(this.ThreadProcPollOnEthernet);
			pollDevicesEthernetThread = new Thread(ethernetThreadStart);
			pollDevicesEthernetThread.Name = "Listener's Receive Thread";
			pollDevicesEthernetThread.ApartmentState = System.Threading.ApartmentState.MTA;
			pollDevicesEthernetThread.Start();
		}
Пример #19
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 override void Initialize(NetworkPackageGenerator packageGenerator, TcpInitInfo initInfo)
 {
     _tcpListener      = new System.Net.Sockets.TcpListener(IPAddress.Parse(initInfo.IpAddress), initInfo.Port);
     _packageGenerator = packageGenerator;
     IpAddresses       = initInfo.IpAddress;
     Port = initInfo.Port;
 }
Пример #21
0
		/// <summary>
		/// Constructor of the TCP service object
		/// </summary>
		/// <param name="port">TCP port number</param>
		public TCPService(int port)
		{
			TcpListener tempTCPListener;
			tempTCPListener = new TcpListener(System.Net.Dns.GetHostAddresses(System.Net.Dns.GetHostName())[0], port);
			tempTCPListener.Start();
			serverSocket = tempTCPListener;
			// serverSocket.setReuseAddress(true);
			// serverSocket.setLoopbackMode(false); // true *disables* loopback
			
			acceptThread = new Thread(AcceptThreadRun);
			acceptThread.IsBackground = true;
			acceptThread.Start();
			
			long inittime = DateTime.Now.Ticks / 10000;
			long starttime = DateTime.Now.Ticks / 10000;
			
			while (true)
			{
				try
				{
					System.Threading.Thread.Sleep(1000);
				}
				catch (System.Threading.ThreadInterruptedException)
				{
				}
				
				long endtime = System.DateTime.Now.Ticks / 10000;
				double dt = (endtime - starttime) / 1000.0;
				starttime = endtime;
				
				Console.WriteLine("{0,10:N} : {1,10:N} kB/s, {2:D} clients", (endtime - inittime) / 1000.0, bytesCount / 1024.0 / dt, clients.Count);
				bytesCount = 0;
			}
		}
Пример #22
0
        /// <summary>
        /// Starts accepting connections.
        /// </summary>
        public void Start()
        {
            if (disposed)
            {
                throw new ObjectDisposedException(this.ToString());
            }

            // This is equivalent to the behavior of TcpListener.Create in .NET 4.5.
            listener = new Net.TcpListener(IPAddress.Any, port);
            //listener.Server.SetSocketOption(SocketOptionLevel.IPv6, SocketOptionName.IPv6Only, 0);

            listener.Start();


            listenerSubscription = Observable
                                   .FromAsync(() => listener.AcceptTcpClientAsync())
                                   .Repeat()
                                   .Select(client => new ReactiveSocket(client))
                                   .Subscribe(socket =>
            {
                connections.Add(socket);
                observable.OnNext(socket);

                IDisposable disposeSubscription = Observable.FromEventPattern <EventHandler, EventArgs>(
                    h => socket.Disposed       += h, h => socket.Disposed -= h)
                                                  .FirstAsync().Subscribe(x =>
                {
                    connections.Remove(socket);
                });

                this.socketDisposable.Add(disposeSubscription);
            });
        }
Пример #23
0
 public Servidor()
 {
     Console.WriteLine ("Iniciando servidor");
     ipAddress = Dns.GetHostEntry("localhost").AddressList[0];
     listener = new TcpListener (ipAddress, porta);
     listener.Start ();
 }
Пример #24
0
 /// <summary>
 /// Starts listening for clients
 /// </summary>
 /// <param name="ipAddress">The IP address to use</param>
 /// <param name="port">The port on which to listen</param>
 public void Start(IPAddress ipAddress, int port)
 {
     _server = new TcpListener(ipAddress, port);
     _server.Start();
     _listenProc = W.Threading.Thread.Create(ListenForClientsProc, ListenForClientsProc_OnComplete);
     IsListening = true;
 }
Пример #25
0
        public TCPListener(int _portNumber, IMessageProcessor _messageProcessor)
        {
            PortNumber = _portNumber;
            MessageProcessor = _messageProcessor;

            tcpListener = new TcpListener(IPAddress.Any, PortNumber);
        }
Пример #26
0
        private void ListenForClients()
        {
            tcplistener = new TcpListener(IPAddress.Loopback, int.Parse(ConfigurationManager.AppSettings["port"]));
            tcplistener.Start();
            try
            {
                while (true)
                {
                    //blocks until a client has connected to the server

                    TcpClient client = tcplistener.AcceptTcpClient();

                    // here was first an message that send hello client
                    //
                    ///////////////////////////////////////////////////
                    //create a thread to handle communication
                    //with connected client
                    Thread clientThread = new Thread(new ParameterizedThreadStart(HandleClientComm));
                    clientThread.Start(client);
                }
            }
            catch (SocketException e)
            {
                if ((e.SocketErrorCode == SocketError.Interrupted))
                {
                }
            }
        }
Пример #27
0
        public const int MAX_PORT = 65535;         // highest port allocatable

        /// <summary>Finds first available port starting at start_port and returns server socket </summary>
        public static System.Net.Sockets.TcpListener createServerSocket(int start_port)
        {
            System.Net.Sockets.TcpListener ret = null;

            while (true)
            {
                try
                {
                    System.Net.Sockets.TcpListener temp_tcpListener;
                    temp_tcpListener = new System.Net.Sockets.TcpListener(start_port);
                    temp_tcpListener.Start();
                    ret = temp_tcpListener;
                }
                catch (System.Net.Sockets.SocketException bind_ex)
                {
                    start_port++;
                    continue;
                }
                catch (System.IO.IOException io_ex)
                {
                }
                break;
            }
            return(ret);
        }
        public void StartServer()
        {
            if (m_SourceForm == null)
            {
                m_SynchronizingObject = m_SourceForm;
            }

            //* Find the IPV4 address of this computer
            string LocalComputerName = System.Net.Dns.GetHostName(); //* same as My.Computer.Name

            System.Net.IPAddress localAddr = GetIPv4Address(LocalComputerName);

            if (localAddr == null)
            {
                localAddr = System.Net.IPAddress.Parse("127.0.0.1");
            }

            try
            {
                server = new TcpListener(localAddr, m_TCPPort);
                server.Start();
                server.BeginAcceptTcpClient(ConnectionAccepted, server);
            }
            catch (SocketException e)
            {
                Console.WriteLine("SocketException: {0}", e);
            }
        }
Пример #29
0
 // constructeur
 public FormServeur()
 {
     InitializeComponent();
     Joueur1 = new Joueur(panelFond, new Point(100, 100),true);
     Joueur2 = new Joueur(panelFond, new Point(100, 150),false); // Cette fois les joueurs sont clairements
     labelScoreJ1.Text = "0";
     labelScoreJ2.Text = "0"; // L'interface n'est plus la même non plus, on dédouble tout.
     pBChargeJ1.Maximum = 1000;
     pBChargeJ1.Minimum = 0;
     pBChargeJ2.Maximum = 1000;
     pBChargeJ2.Minimum = 0;
     try
     {
         IPAddress ipAd = IPAddress.Parse("127.0.0.1"); //on utilise l'adresse ip locale
         myList = new TcpListener(ipAd, 8001);   //initialisation du listener
         myList.Start();                         // on écoute sur le port
         Console.WriteLine("The server is running at port 8001...");
         Console.WriteLine("The local End point is :" + myList.LocalEndpoint); // Ces trois lignes ci ne servent qu'a controler via la console ce qui se passe.
         Console.WriteLine("Waiting for a connection.....");
         cl = myList.AcceptTcpClient();          // dés qu'il y a une connection on peut passer a la suite
         Console.WriteLine("Connection accepted from " + cl.Client.RemoteEndPoint);
         stm = cl.GetStream(); // le flux de données est créé
      }
      catch (Exception e)
     {
         Console.WriteLine("Error..... " + e.StackTrace);
         Console.ReadLine();
     }
     th1 = new Thread(Launch); // on lance le thread qui va lire le flux
     th1.Name = "Serveur";
     th1.Start();
 }
        private void startServer()
        {
            try
            {
                server = new TcpListener(IPAddress.Any, 8888);
                server.Start();
                stopBtn.Enabled  = true;
                startBtn.Enabled = false;

                txtReceive.AppendText(">> Waiting For Connection...\n");
                if (InvokeRequired)
                {
                    this.Invoke(new Action(() => AcceptClients()));
                    return;
                }
                AcceptClients();
                STR           = new StreamReader(client.GetStream());
                STW           = new StreamWriter(client.GetStream());
                STW.AutoFlush = true;

                txtReceive.AppendText("\n**Connection Established**\n");
                txtReceive.AppendText("==========\n");

                receivingWorker.RunWorkerAsync();
                sendingWorker.WorkerSupportsCancellation   = true;
                receivingWorker.WorkerSupportsCancellation = true;
            }

            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
            }
        }
Пример #31
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;
        }
Пример #32
0
        private void ListenForClients(object olistener)
        {
            System.Net.Sockets.TcpListener listener = olistener as System.Net.Sockets.TcpListener;

            listener.Start();


            while (!_cancelToken.IsCancellationRequested && !_shutdown)
            {
                try
                {
                    //blocks until a client has connected to the server
                    TcpClient client = listener.AcceptTcpClient();

                    // Wait for a client, spin up a thread.
                    var clientThread = new Thread(new ParameterizedThreadStart(HandleNewClient));
                    clientThread.Start(client);
                }
                catch (SocketException ex)
                {
                    if (ex.SocketErrorCode == SocketError.Interrupted)
                    {
                        break;
                    }
                }
            }
        }
Пример #33
0
        public static async Task AcceptClientsAsync(TcpListener listener, CancellationToken cancel)
        {
            await Task.Yield();

            while (!cancel.IsCancellationRequested)
            {
                try
                {
                    var timeoutTask = Task.Delay(2000);
                    var acceptTask = listener.AcceptTcpClientAsync();

                    await Task.WhenAny(timeoutTask, acceptTask);
                    if (!acceptTask.IsCompleted)
                        continue;

                    var client = await acceptTask;
                    HandleClientAsync(client, cancel);
                }
                catch (Exception aex)
                {
                    var ex = aex.GetBaseException();
                    Console.WriteLine("Accepting error: " + ex.Message);
                }
            }
        }
Пример #34
0
 public PcapTcpStream(ushort localTcpPort, bool useSsl, int idleTimeoutMilliSeconds) : this(useSsl, idleTimeoutMilliSeconds)
 {
     this.socketState = TcpSocketState.Closed;
     this.tcpListener = new System.Net.Sockets.TcpListener(System.Net.IPAddress.Any, (int)localTcpPort);
     tcpListener.Start();
     this.socketState = TcpSocketState.Listening;
 }
Пример #35
0
        static void BackupProcess()
        {
            Console.WriteLine("I am backup!");
            
            IPAddress ipAddress = Dns.GetHostEntry("localhost").AddressList[0];
            TcpListener listener = new TcpListener(ipAddress, port);
            listener.Start();
            Socket sock = listener.AcceptSocket();
            Stream str = new NetworkStream(sock);
            StreamReader sr = new StreamReader(str);

            string line = "-1";

            try
            {
                while (true)
                    line = sr.ReadLine();
            }
            catch(IOException)
            { 
                sr.Close();
                listener.Stop();

                PrimaryProcess(Convert.ToInt32(line) + 1);
            }
        }
Пример #36
0
        private static readonly String s_newline = Environment.NewLine;         //$NON-NLS-1$

        public PlayerSessionManager()
        {
            m_debuggerCallbacks = new DefaultDebuggerCallbacks();

            m_serverSocket = null;
            m_prefs        = new System.Collections.Hashtable();

            // manager
            setPreference(SessionManager.PREF_ACCEPT_TIMEOUT, 120000);             // 2 minutes
            setPreference(SessionManager.PREF_URI_MODIFICATION, 1);

            // session

            // response to requests
            setPreference(SessionManager.PREF_RESPONSE_TIMEOUT, 750);             // 0.75s
            setPreference(SessionManager.PREF_CONTEXT_RESPONSE_TIMEOUT, 1000);    // 1s
            setPreference(SessionManager.PREF_GETVAR_RESPONSE_TIMEOUT, 1500);     // 1.5s
            setPreference(SessionManager.PREF_SETVAR_RESPONSE_TIMEOUT, 5000);     // 5s
            setPreference(SessionManager.PREF_SWFSWD_LOAD_TIMEOUT, 5000);         // 5s

            // wait for a suspend to occur after a halt
            setPreference(SessionManager.PREF_SUSPEND_WAIT, 7000);

            // invoke getters by default
            setPreference(SessionManager.PREF_INVOKE_GETTERS, 1);

            // hierarchical variables view
            setPreference(SessionManager.PREF_HIERARCHICAL_VARIABLES, 0);
        }
        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();
            }
        }
Пример #38
0
    public HttpServer(int port)
    {
      prefixes.TryAdd(
        "/favicon.ico",
        new StaticHandler(
          new ResourceResponse(HttpCode.Ok, "image/icon", "favicon"))
        );
      prefixes.TryAdd(
        "/static/browse.css",
        new StaticHandler(
          new ResourceResponse(HttpCode.Ok, "text/css", "browse_css"))
        );
      RegisterHandler(new IconHandler());

      listener = new TcpListener(new IPEndPoint(IPAddress.Any, port));
      listener.Server.Ttl = 32;
      listener.Server.UseOnlyOverlappedIO = true;
      listener.Start();

      RealPort = (listener.LocalEndpoint as IPEndPoint).Port;

      NoticeFormat(
        "Running HTTP Server: {0} on port {1}", Signature, RealPort);
      ssdpServer = new SsdpHandler();

      timeouter.Elapsed += TimeouterCallback;
      timeouter.Enabled = true;

      Accept();
    }
Пример #39
0
        private bool startListen()
        {
            try
            {
                if (tcpListener == null)
                    tcpListener = new TcpListener(IPAddress.Any, tcpPort);

                if (udpClient == null || udpClosed)
                {
                    udpClient = new UdpClient(udpPort);
                    //udpClient = new UdpClient(udpPort, AddressFamily.InterNetwork);
                    udpClosed = false;
                }

                if (udpListenThread == null || !udpListenThread.IsAlive)
                {
                    udpListenThread = new Thread(new ThreadStart(listenForUdpClients));
                    udpListenThread.IsBackground = true;
                    udpListenThread.Start();
                }
                if (tcpListenThread == null || !tcpListenThread.IsAlive)
                {
                    tcpListenThread = new Thread(new ThreadStart(listenForTcpClients));
                    tcpListenThread.IsBackground = true;
                    tcpListenThread.Start();
                }
                Trace.WriteLine("Server started on TCP-Port: " + tcpPort + " and UDP-Port: " + udpPort);
                return true;
            }
            catch
            {
                Trace.WriteLine("Couldn't start server on Tcp-Port: " + tcpPort + " and Udp-Port: " + udpPort);
                return false;
            }
        }
Пример #40
0
 public void Start(int port)
 {
     _keepRunning = true;
     _tcpListener = new TcpListener(IPAddress.Any, port);
     _listenThread = new Thread(ListenForConnections);
     _listenThread.Start();
 }
Пример #41
0
 // starts up the listener thread and heartbeat
 public bool Start() {
     bool worked = false;
     int attempts = 0;
     int attemptsMax = 20;
     int port = world.config.GetInt( "Port" );
     do {
         try {
             listener = new TcpListener( IPAddress.Any, port );
             listener.Start();
             worked = true;
         } catch( Exception ex ) {
             world.log.Log( "Could not start listening on port {0}, trying next port. ({1})", LogType.Error,
                           port, ex.Message );
             port++;
             attempts++;
         }
     } while( !worked && attempts < attemptsMax );
     if( !worked ) {
         world.log.Log( "Could not start listening after {0} tries. Giving up!", LogType.FatalError, attemptsMax );
         return false;
     }
     
     sessions = new List<Session>();
     world.log.Log( "Server.Run: now accepting connections at port {0}.", LogType.Debug, port );
     return true;
 }
Пример #42
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();
            }
Пример #43
0
 public void Start()
 {
     _stop = false;
     _listener = new TcpListener(IPAddress.Any, _port);
     _listener.Start();
     _listener.BeginAcceptSocket(OnAcceptSocket, null);
 }
Пример #44
0
        protected async Task <Stream> AcceptStreamAsync(System.Net.Sockets.TcpListener listener)
        {
            try
            {
                LoggerHelper.Debug($"Accept stream on {listener.LocalEndpoint.ToString()}");
                Socket = await listener.AcceptSocketAsync();

                BaseStream   = new NetworkStream(Socket);
                LastActivity = DateTime.Now;

                if (IsDataConnection)
                {
                    if (Configuration.ShouldEncrypt && Configuration.EncryptionType == FtpEncryption.Explicit)
                    {
                        await ActivateEncryptionServerAsync();
                    }
                }
                else
                {
                    if (Configuration.ShouldEncrypt && Configuration.EncryptionType == FtpEncryption.Implicit)
                    {
                        await ActivateEncryptionServerAsync();
                    }
                }
                return(this);
            }
            catch (Exception exception)
            {
                LoggerHelper.Error($"Could accept connect {listener.LocalEndpoint.ToString()} :{exception.ToString()}");
                throw;
            }
        }
        public override void Initiate()
        {
            base.Initiate();

            Console.WriteLine("Web communicator");
            Console.Write("Starting socket...");
            try
            {
                server = new TcpListener(IPAddress.Any, portNumber);
                server.Start();
            }
            catch
            {
                Program.Shutdown("Server Startup Failed");
                return;
            }
            Console.WriteLine("Done");

            while (Program.Update)
            {
                TcpClient newClient = server.AcceptTcpClient();

                ThreadPool.QueueUserWorkItem(new WaitCallback(ProcessClient), newClient);
            }
        }
Пример #46
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());
     }
 }
Пример #47
0
        public ServerBase(string ip, int port)
        {
            var bindIP = IPAddress.None;

            if (!IPAddress.TryParse(ip, out bindIP))
            {
                Log.Normal($"Server can't be started: Invalid IP-Address ({ip})");
                Console.ReadKey(true);

                Environment.Exit(0);
            }

            try
            {
                listener = new TcpListener(bindIP, port);
                listener.Start();

                if (isRunning = listener.Server.IsBound)
                    new Thread(AcceptConnection).Start(200);
            }
            catch (Exception ex)
            {
                ExceptionLog.Write(ex);

                Log.Error(ex.Message);
            }
        }
Пример #48
0
 void HandleThreadStart()
 {
     try {
         TCL = new System.Net.Sockets.TcpListener(new System.Net.IPEndPoint(System.Net.IPAddress.Any, 10112));
         TCL.Start();
         do
         {
             try {
                 System.Net.Sockets.Socket S = TCL.AcceptSocket();
                 FeuerwehrCloud.Helper.Logger.WriteLine("|  < [FAX] *** Incoming notification");
                 S.Blocking = false;
                 S.BeginReceive(buffer, 0, DEFAULT_SIZE - dataRecieved,
                                System.Net.Sockets.SocketFlags.None, new AsyncCallback(HandleAsyncCallback), S);
                 if (IsTerminating)
                 {
                     break;
                 }
             } catch (Exception e2x) {
             }
         } while (true);
     } catch (Exception ex) {
         if (ex.Message.Contains("already in use"))
         {
             FeuerwehrCloud.Helper.Logger.WriteLine("Kann FeuerwehrCloud-Server FaxModul nicht starten!");
         }
     }
 }
Пример #49
0
        public const int MAX_PORT = 65535;         // highest port allocatable

        /// <summary>Finds first available port starting at start_port and returns server socket </summary>
        public static System.Net.Sockets.TcpListener createServerSocket(int start_port)
        {
            System.Net.Sockets.TcpListener ret = null;

            while (true)
            {
                try
                {
                    System.Net.Sockets.TcpListener temp_tcpListener;
                    temp_tcpListener = new System.Net.Sockets.TcpListener(start_port);
                    temp_tcpListener.Start();
                    ret = temp_tcpListener;
                }
                catch (System.Net.Sockets.SocketException bind_ex)
                {
                    //Trace.error("util.createServerSocket()",bind_ex.Message);
                    start_port++;
                    continue;
                }
                catch (System.IO.IOException io_ex)
                {
                    //Trace.error("Util.createServerSocket():2" + io_ex.Message);
                }
                break;
            }
            return(ret);
        }
Пример #50
0
        public HtmlGetServer(int Port, TcpListener listener)
        {
            Listener = listener;
            if (Listener==null)
                Listener = new TcpListener(IPAddress.Any, Port);
            Listener.Start();

            while (true)
            {
               try
               {
                    ThreadPool.QueueUserWorkItem(new WaitCallback(ClientThread), Listener.AcceptTcpClient());
                }
               catch { }
                // Принимаем новых клиентов. После того, как клиент был принят, он передается в новый поток (ClientThread)
                // с использованием пула потоков.

                /*
                // Принимаем нового клиента
                TcpClient Client = Listener.AcceptTcpClient();
                // Создаем поток
                Thread Thread = new Thread(new ParameterizedThreadStart(ClientThread));
                // И запускаем этот поток, передавая ему принятого клиента
                Thread.Start(Client);
                */
            }
        }
Пример #51
0
 private void StartListen2()
 {
     //Create an instance of TcpListener to listen for TCP connection.
     var tcpListener = new TcpListener(SampleTcpPort);
     try
     {
         while (true)
         {
             tcpListener.Start();
             //Program blocks on Accept() until a client connects.
             Socket soTcp = tcpListener.AcceptSocket();
             Console.Message = ("SampleClient is connected through TCP.");
             OnChanged(EventArgs.Empty);
             var received = new Byte[512];
             soTcp.Receive(received, received.Length, 0);
             String dataReceived = System.Text.Encoding.ASCII.GetString(received);
             Console.Message=(dataReceived);
             String returningString = "The Server got your message through TCP: " +
                                      dataReceived; OnChanged(EventArgs.Empty);
             Byte[] returningByte = System.Text.Encoding.ASCII.GetBytes
                 (returningString.ToCharArray());
             //Returning a confirmation string back to the client.
             soTcp.Send(returningByte, returningByte.Length, 0);
         }
     }
     catch (SocketException se)
     {
         Console.Message = ("A Socket Exception has occurred!" + se); OnChanged(EventArgs.Empty);
     }
 }
Пример #52
0
 public TCPServer(int port)
 {
     listener = new TcpListener(IPAddress.Any, port);
     player = new AI(this);
     listener.Start();
     Start();
 }
Пример #53
0
        public static void InitalizeListener(int port)
        {
            _listener = new System.Net.Sockets.TcpListener(_ip, port);
            _listener.Start();

            System.Threading.Timer _t = new System.Threading.Timer(Listen, null, 0, 100);
        }
Пример #54
0
        public async Task Start(string remoteServerIp, ushort remoteServerPort, ushort localPort, string localIp, byte[] byteMapClient2Setver, byte[] byteMapSetver2Client)
        {
            //var clients = new ConcurrentDictionary<IPEndPoint, TcpClient>();

            IPAddress localIpAddress = string.IsNullOrEmpty(localIp) ? IPAddress.IPv6Any : IPAddress.Parse(localIp);
            var       server         = new System.Net.Sockets.TcpListener(new IPEndPoint(localIpAddress, localPort));

            server.Server.SetSocketOption(SocketOptionLevel.IPv6, SocketOptionName.IPv6Only, false);
            server.Start();

            Console.WriteLine($"TCP proxy started {localPort} -> {remoteServerIp}|{remoteServerPort}");
            while (true)
            {
                try
                {
                    var remoteClient = await server.AcceptTcpClientAsync();

                    remoteClient.NoDelay = true;
                    var ips = await Dns.GetHostAddressesAsync(remoteServerIp);

                    new TcpClient(remoteClient, new IPEndPoint(ips.First(), remoteServerPort), byteMapClient2Setver, byteMapSetver2Client);
                }
                catch (Exception ex)
                {
                    Console.ForegroundColor = ConsoleColor.Red;
                    Console.WriteLine(ex);
                    Console.ResetColor();
                }
            }
        }
Пример #55
0
 public Server()
 {
     config = new INIReader(System.IO.File.ReadAllLines("config.ini"));
     chat = new ServerChat();
     instance = this;
     vehicleController = new ServerVehicleController();
     api = new ServerApi(this);
     gamemodeManager = new GamemodeManager(api);
     gamemodeManager.loadFromFile("gamemodes/" + config.getString("gamemode"));
     server = new TcpListener(IPAddress.Any, config.getInt("game_port"));
     server.Start();
     server.BeginAcceptTcpClient(onIncomingConnection, null);
     playerpool = new List<ServerPlayer>();
     Timer timer = new Timer();
     timer.Elapsed += onBroadcastTimer;
     timer.Interval = config.getInt("broadcast_interval");
     timer.Enabled = true;
     timer.Start();
     UDPStartPort = config.getInt("udp_start_port");
     Timer timer_slow = new Timer();
     timer_slow.Elapsed += timer_slow_Elapsed;
     timer_slow.Interval = config.getInt("slow_interval");
     timer_slow.Enabled = true;
     timer_slow.Start();
     http_server = new HTTPServer();
     Console.WriteLine("Started game server on port " + config.getInt("game_port").ToString());
     Console.WriteLine("Started http server on port " + config.getInt("http_port").ToString());
 }
        public EmbeddedSmtpServer(IPAddress address, int port = 25)
        {
            Address = address;
            Port = port;

            Listener = new TcpListener(Address, port);
        }
Пример #57
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();
         }
     }
 }
Пример #58
0
        public void Start()
        {
            IPEndPoint ip = new IPEndPoint(IPAddress.Any, _port);

            _listener = new System.Net.Sockets.TcpListener(ip);
            _listener.Start();
            _listener.BeginAcceptTcpClient(AcceptCallback, _listener);
        }
Пример #59
0
 public EpoxyListener(EpoxyTransport parentTransport, IPEndPoint listenEndpoint)
 {
     this.parentTransport = parentTransport;
     listener             = new System.Net.Sockets.TcpListener(listenEndpoint);
     serviceHost          = new ServiceHost(parentTransport);
     connections          = new HashSet <EpoxyConnection>();
     shutdownTokenSource  = new CancellationTokenSource();
 }
Пример #60
0
 /*
  * @see Flash.Tools.Debugger.SessionManager#stopListening()
  */
 public override void stopListening()
 {
     if (m_serverSocket != null)
     {
         m_serverSocket.Stop();
         m_serverSocket = null;
     }
 }