示例#1
1
        static void Main(string[] args)
        {
            update_bases();
            TcpListener Listen = new TcpListener(IPAddress.Any, 1488);
            Listen.Start();
            Console.WriteLine("[Server is online]");
            int games = 0;
            while (true)
            {
                //кто-то подсоединился
                TcpClient Client = Listen.AcceptTcpClient();
                Console.Write("[Client connected!]");
                NetworkStream ns = Client.GetStream();

                //Проверяем, есть ли кто-то в очереди
                if (Waiter != null)
                {
                    //в очереди кто-то есть, создаем новую игру
                    Games.Add(new Game(games++, Waiter, Client, timeOfGame, GenerateWord()));
                    Waiter = null;
                }
                else
                {
                    //очеред пуста, закидываем туда клиента
                    Waiter = Client;
                }
            }
        }
示例#2
0
        static void Main(string[] args)
        {
            TcpListener server = null;
            try
            {
                Int32 port = Convert.ToInt32(args[0]);
                IPAddress localAddr = IPAddress.Parse("127.0.0.1");
                server = new TcpListener(localAddr, port);
                server.Start();
                int numberOfClients = 0;
                while (true)
                {
                    Console.WriteLine("Waiting for a connection...");
                    TcpClient client = server.AcceptTcpClient();
                    Console.WriteLine((++numberOfClients).ToString() + " Connected!");

                    HandleClient handleClient = new HandleClient(client);
                    Thread myThread = new Thread(new ThreadStart(handleClient.Communicate));
                    myThread.Name = Convert.ToString(numberOfClients);
                    myThread.IsBackground = true;
                    myThread.Start();
                }
            }
            finally
            {
                server.Stop();
            }
        }
示例#3
0
文件: Server.cs 项目: ZacJ/BroodLord
 public Server()
 {
     port = 41337;
     listener = new TcpListener(port);
     otherListener = new TcpListener(41338);
     streams = new List<NetworkStream>();
 }
	/// <summary>
	/// Start a HTTP server.
	/// </summary>
	/// <param name="port">Port number.</param>
	public bool StartServer(int port)
	{
		try
		{
			Debug.Log("Starting a server...");
			server = new TcpListener(IPAddress.Parse("127.0.0.1"), port);
			server.Start();

			listenThread = new Thread(Listen);
			listenThread.Start();

			Debug.Log("The server is started.");
		}
		catch (Exception e)
		{
			Debug.LogError(e);

			if (server != null)
				server.Stop();

			server = null;

			return false;
		}

		return true;
	}
示例#5
0
        public void Start()
        {
            TcpListener listener = new TcpListener(IPAddress, Port);
            listener.Start();

            Console.WriteLine("Server is running, good luck!");

            while (true)
            {
                var client = new NetworkClient(listener.AcceptTcpClient());
                connectedClients.Add(client);

                Task.Factory.StartNew(() =>
                {
                    try
                    {
                        HandleConnectedClient(client);
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine(ex.Message);
                        Console.WriteLine(ex.StackTrace);
                    }
                },TaskCreationOptions.LongRunning);

                Console.WriteLine("User Connected. Now you have {0} users connected", connectedClients.Count);
            }
        }
示例#6
0
        Program()
        {
            IPAddress ip = Info.GetIp();
            TcpListener listener = new TcpListener(ip,Info.Port);
            storage = new DataStorage();
            listener.Start();
            int counter = 0;
            Console.WriteLine("Server started: {0}",DateTime.Now);
            Console.WriteLine("Server ip: {0}", ip);
            Console.WriteLine("Server port: {0}",Info.Port);

            while (true)
            {
                TcpClient newClient = listener.AcceptTcpClient();
                if (!IsMonitor(newClient))
                {
                    counter++;
                    Console.WriteLine("is client");
                    Client client = new Client(newClient, this, counter, storage);
                    clients.Add(client);
                }
                else if (_monitor != null)
                {
                    if (!_monitor.TcpClient.Connected)
                    {
                        _monitor = new Monitor(newClient,this,clients, storage);
                    }
                }
                else
                {
                    _monitor = new Monitor(newClient,this,clients, storage);
                }
            }
        }
示例#7
0
 public DispatchLoop(TcpListener listener, ILogger logger, 
                   IProtocolFactory protoFactory)
 {
     this.listener     = listener;
     this.logger       = logger;
     this.protoFactory = protoFactory;
 }
        public void StartServer()
        {
            TcpListener server = new TcpListener(IPAddress.Parse("192.168.0.13"), 14500);

            server.Start();
            Console.WriteLine("Server has started on 127.0.0.1:14500.{0}Waiting for a connection...", Environment.NewLine);

            while (true)
            {
                Socket client = server.AcceptSocket();

                Console.WriteLine("A client connected.");

                var childSocketThread = new Thread(() =>
                {
                    byte[] data = new byte[4096];
                    int size = client.Receive(data);
                    if (size > 4096) //the packet is too god damn high
                    {
                        Console.Write("Client tried to send packet above 4096 bytes");
                        return;
                    }
                    HandlePacket(client,data);
                    Console.WriteLine("Recieved data:");
                    for (int i = 0; i < size; i++)
                    {
                        Console.Write(Convert.ToChar(data[i]));
                    }
                    Console.WriteLine();
                    client.Close();
                });

                childSocketThread.Start();
            }
        }
示例#9
0
 public static void Main()
 {
     TcpListener tcpListener = new TcpListener(10);
     tcpListener.Start();
     Socket socketForClient = tcpListener.AcceptSocket();
     if (socketForClient.Connected)
     {
         Console.WriteLine("Client connected");
         NetworkStream networkStream = new NetworkStream(socketForClient);
         System.IO.StreamWriter streamWriter =
         new System.IO.StreamWriter(networkStream);
         System.IO.StreamReader streamReader =
         new System.IO.StreamReader(networkStream);
         string theString = "Sending";
         streamWriter.WriteLine(theString);
         Console.WriteLine(theString);
         streamWriter.Flush();
         theString = streamReader.ReadLine();
         Console.WriteLine(theString);
         streamReader.Close();
         networkStream.Close();
         streamWriter.Close();
     }
     socketForClient.Close();
     Console.WriteLine("Exiting...");
 }
示例#10
0
    public static int GetFreePort()
    {
        TcpListener tcpListener = default(TcpListener);
        int port = 0;
        try
        {
            var ipAddress = Dns.GetHostEntry("localhost").AddressList[0];

            tcpListener = new TcpListener(ipAddress, 0);
            tcpListener.Start();
            string s = tcpListener.LocalEndpoint.ToString();
            s = s.Substring(s.IndexOf("]:")+2);
            port = int.Parse(s);
            return port;
        }
        catch (SocketException)
        {
        }
        finally
        {
            if (tcpListener != null)
                tcpListener.Stop();
        }

        return port;
    }
示例#11
0
    public static void Main(String[] args)
    {
        TcpListener server=null;

        try {
          //Echo servers listen on port 7
          int portNumber = 7;

          //Echo server first binds to port 7
          server = new TcpListener(portNumber);
          //Server starts listening
          server.Start();

          //Echo server loops forever, listening for clients
          for(;;) {
        //Accept the pending client connection and return a client
        //initialized for communication
        //This method will block until a connection is made
        EchoServer es = new EchoServer(server.AcceptTcpClient());

        //Allow this conversation to run in a new thread
        Thread serverThread = new Thread(
        new ThreadStart(es.Conversation));
        serverThread.Start();

        //Loop back up and wait for another client
        //Another thread is servicing this client
          }
        } catch (Exception e) {
        Console.WriteLine(e+" "+e.StackTrace);
        } finally {
        //Release the port and stop the server
        server.Stop();
        }
    }
示例#12
0
 internal ServerState()
 {
     this.PortNumber = String.Empty;
     this.Password = String.Empty;
     this.MainPort = null;
     this.Clients = new Dictionary<String, TaskInfo>();
     this.wChatClipboard = null;
     this.Transmitting = false;
     this.WorkEnd = false;
     this.VideoOn = false;
     this.SelectingArea = false;
     this.StreamingSem = null;
     this.Spawner = null;
     this.Transfer = null;
     this.Streamer = null;
     this.Area = new Rectangle(0,0,0,0);
     this.hWnd = IntPtr.Zero;
     this.dUpdateHistory = null;
     this.dUpdateClipboard = null;
     this.dSendClipboard = null;
     this.PreviousBMP = null;
     this.CurrentBMP = null;
     this.SelectedWindowOffsetX = 0;
     this.SelectedWindowOffsetY = 0;
 }
示例#13
0
    public static void Run()
    {
        var listener = new TcpListener(IPAddress.Loopback, 8181);
        listener.Start();
        using (var client = listener.AcceptTcpClient())
        using (var stream = client.GetStream())
        using (var reader = new StreamReader(stream))
        using (var writer = new StreamWriter(stream))
        {
            Console.WriteLine(reader.ReadLine());
            Console.WriteLine(reader.ReadLine());
            Console.WriteLine(reader.ReadLine());
            Console.WriteLine(reader.ReadLine());
            Console.WriteLine(reader.ReadLine());
            Console.WriteLine(reader.ReadLine());

            writer.WriteLine("HTTP/1.1 101 Web Socket Protocol Handshake");
            writer.WriteLine("Upgrade: WebSocket");
            writer.WriteLine("Connection: Upgrade");
            writer.WriteLine("WebSocket-Origin: http://localhost:8080");
            writer.WriteLine("WebSocket-Location: ws://localhost:8181/websession");
            writer.WriteLine("");
        }
        listener.Stop();
    }
示例#14
0
        public void Run()
        {
            _broadcaster = new Broadcaster();

            IPAddress ip = IPAddress.Parse(_servername);
            TcpListener listener = new TcpListener(ip, _port);

            /* Gør så at serveren kan skrive input*/
            Thread serverInputThread = new Thread(HandleInput);
            serverInputThread.Start();

            _running = true;

            listener.Start();

            Console.WriteLine("Skriv \'new\' for at starte en ny auktion.");

            while (_running)
            {
                System.Console.WriteLine("Server klar til bruger");
                /* En socket forbinder*/
                Socket clientSocket = listener.AcceptSocket();

                /* Lav en ny client handler til forbindelsen */
                ClientHandler handler = new ClientHandler(clientSocket, _broadcaster);
                handler.SetAuction(_auction);

                /* Start det i en ny tråd */
                Thread clientThread = new Thread(handler.RunClient);

                /* Start trådene */
                clientThread.Start();
            }
        }
示例#15
0
 public void BeginLister()
 {
     while (true)
     {
         try
         {
             IPAddress[] Ips = Dns.GetHostAddresses("");
             string GetIp = Ips[0].ToString();
             Listener = new TcpListener(IPAddress .Parse (GetIp ),8888);
             Listener.Start();
             CheckForIllegalCrossThreadCalls = false;
             butBeginSever.Enabled = false;
             this.Text = "服务器已经开启.....";
             SocketClient = Listener.AcceptSocket();
             NetStream = new NetworkStream(SocketClient );
             ServerWriter = new StreamWriter(NetStream );
             ServerReader = new StreamReader(NetStream );
             if (SocketClient.Connected)
             {
                 MessageBox.Show("客户端连接成功!","服务器消息",MessageBoxButtons .OK ,MessageBoxIcon.Information );
             }
         }
         catch { }
     }
 }
    public void Start(int port)
    {
        if (listener != null && listener.Server.IsBound)
        {
            return;
        }

        this.port = port;

        IPEndPoint ipEnd = new IPEndPoint(IPAddress.Any, port);
        listener = new TcpListener(ipEnd);

        try
        {
            listener.Start();
            running = true;
            if (LOGGER.IsInfoEnabled)
            {
                LOGGER.Info("Push Server Simulator is successfully started on port " + port.ToString());
            }
        }
        catch (Exception e)
        {
            if (LOGGER.IsErrorEnabled)
            {
                LOGGER.Error("Error occured while trying to start Push Server Simulator on port " + port.ToString() + " . Message: " + e.Message);
            }
        }

        thread = new Thread(new ThreadStart(listen));
        thread.Start();
    }
示例#17
0
	public int Start ()
	{
		bool processed;
		
		Console.WriteLine ("Touch.Unit Simple Server listening on: {0}:{1}", Address, Port);
		server = new TcpListener (Address, Port);
		try {
			server.Start ();
			
			do {
				using (TcpClient client = server.AcceptTcpClient ()) {
					processed = Processing (client);
				}
			} while (!AutoExit || !processed);
		}
		catch (Exception e) {
			Console.WriteLine ("[{0}] : {1}", DateTime.Now, e);
			return 1;
		}
		finally {
			server.Stop ();
		}
		
		return 0;
	}
示例#18
0
        public static void Main(string[] args)
        {
            Console.WriteLine("Server start");
            int port = 55555;
            var listener = new TcpListener(IPAddress.Loopback, port);
            listener.Start();
            Console.WriteLine("start listening");

            var client = listener.AcceptTcpClientAsync().Result;
            var stream = client.GetStream();

            var reader = new StreamReader(stream);
            
            Console.WriteLine("Connected");
            
            var data = reader.ReadLine();

            if (data == null) {
                Console.WriteLine("data is null");
            } 
            else 
            {
                Console.WriteLine(data);
            }            
        }
示例#19
0
文件: Server.cs 项目: srfoster/June
 public Server(CallResponseQueue queue)
 {
     this.queue = queue;
       this.tcpListener = new TcpListener(IPAddress.Loopback, 3000);
       this.listenThread = new Thread(new ThreadStart(ListenForClients));
       this.listenThread.Start();
 }
示例#20
0
        /// <summary>
        /// Creates a pair of connected NetworkStreams and invokes the provided <paramref name="func"/>
        /// with them as arguments.
        /// </summary>
        private static async Task RunWithConnectedNetworkStreamsAsync(Func<NetworkStream, NetworkStream, Task> func)
        {
            var listener = new TcpListener(IPAddress.Loopback, 0);
            try
            {
                listener.Start(1);
                var clientEndpoint = (IPEndPoint)listener.LocalEndpoint;

                using (var client = new TcpClient(clientEndpoint.AddressFamily))
                {
                    Task<TcpClient> remoteTask = listener.AcceptTcpClientAsync();
                    Task clientConnectTask = client.ConnectAsync(clientEndpoint.Address, clientEndpoint.Port);

                    await Task.WhenAll(remoteTask, clientConnectTask);

                    using (TcpClient remote = remoteTask.Result)
                    using (NetworkStream serverStream = remote.GetStream())
                    using (NetworkStream clientStream = client.GetStream())
                    {
                        await func(serverStream, clientStream);
                    }
                }
            }
            finally
            {
                listener.Stop();
            }
        }
		BlockingTcpListener(Loop loop)
			: base(loop)
		{
			TcpListener = new TcpListener(loop);
			Listener = TcpListener as Listener;
			Handle = TcpListener;
		}
示例#22
0
	public void Start ()
	{
		tcpListener = new TcpListener (LocalEndPoint);
		tcpListener.Start ();
		listenThread = new Thread (new ThreadStart (Listen));
		listenThread.Start ();
	}
示例#23
0
        /// <summary>
        /// Gets request from client, and sends back file/folder to encrypt
        /// </summary>
        static void handleRequest(TcpListener listener)
        {
            while (true)
            {
                int bytesRead;
                byte[] buffer = new byte[1024];
                string test = null;

                Socket s = listener.AcceptSocket();
                Console.WriteLine("Connection accepted from " + s.RemoteEndPoint);

                bytesRead = s.Receive(buffer);

                char cc = ' ';

                Console.WriteLine("Recieved...");
                for (int i = 0; i < bytesRead - 1; i++)
                {
                    //Console.Write(Convert.ToChar(buffer[i]));
                    cc = Convert.ToChar(buffer[i]);
                    test += cc.ToString();
                }

                Console.WriteLine(test);
                string message = "files encrypted.";

                ASCIIEncoding asen = new ASCIIEncoding();
                s.Send(asen.GetBytes(message));
                s.Close();
                Console.WriteLine("sent bytes back");
            }
        }
示例#24
0
    static void Main(string[] args)
    {
        byte[] quote = Encoding.ASCII.GetBytes("Insanity: doing the same thing over and over again and expecting different results. - Albert Einstein");

        var loop = new UVLoop();

        var listener = new TcpListener("0.0.0.0", 17, loop);

        listener.ConnectionAccepted += (Tcp connection) =>
        {
            connection.ReadCompleted += (ByteSpan data) =>
            {
                unsafe
                {
                    fixed (byte* pQuote = quote)
                    {
                        connection.TryWrite(new ByteSpan(pQuote, quote.Length));
                    }
                }
            };

            connection.ReadStart();
        };

        listener.Listen();
        loop.Run();
    }
 public static void Main(String[] args)
 {
     TcpListener server = new TcpListener(int.Parse(args[0]));
     server.Start();
     TcpClient client = server.AcceptTcpClient();
     NetworkStream stream = client.GetStream();
     StreamReader reader = new StreamReader(stream);
     String s = reader.ReadLine();
     String[] strings = s.Split();
     StreamWriter writer;
     if (strings[0] != "GET") {
       writer = new StreamWriter(stream);
       writer.WriteLine
              ("HTTP/1.0 501 Not Implemented");
       writer.WriteLine();
     } else {
        String filename = strings[1];
        while(reader.ReadLine() != "");
        writer = new StreamWriter(stream);
        writer.WriteLine("HTTP/1.0 200 OK");
        writer.WriteLine("Content-type: text/plain");
        writer.WriteLine();
        StreamReader file = new StreamReader(filename);
        String z = file.ReadToEnd();
        writer.WriteLine(z);
        writer.Flush();
        writer.Close();
        file.Close();
     }
     client.Close();
     stream.Close();
     reader.Close();
     writer.Close();
     server.Stop();
 }
示例#26
0
        /* Constructor */
        public Server()
        {
            //create folder "Plugins" if it doesn't already exists
            _PluginLocation=Environment.CurrentDirectory;
            _PluginLocation += "\\Plugins\\";
            if (!Directory.Exists(_PluginLocation))
            {
                try
                {
                    Directory.CreateDirectory(_PluginLocation);
                }
                catch (Exception e)
                {
                    Console.WriteLine(e.Message + "- Plugin-Folder could not be created");
                    Console.ReadLine();
                    Environment.Exit(1);
                }
            }

            try
            {
                //create listener - second param = port
                TcpListener = new TcpListener(IPAddress.Any, 8080);
            }
            catch (Exception) { throw; }
        }
示例#27
0
    protected override void Execute()
    {
        TcpListener server = null;
        NetworkStream stream = null;
        TcpClient client = null;

        server = new TcpListener(8080);
        server.Start();

        byte[] buffer = new byte[150 * 1024];
        int i = 0;
        logger.Log("Thread Start");
        for(;;){
            client = server.AcceptTcpClient();
            stream = client.GetStream();

            while ((i = stream.Read(buffer, 0, buffer.Length)) != 0){
                retrievedPacket(i, buffer);
                i = 0;

                if(terminate) break;
            }
            client.Close();
            Thread.Sleep(1000 / 30);
            if(terminate) break;
        }
        server.Stop();
        logger.Log("Thread Stop");
    }
示例#28
0
    } // end method DisplayMessage

    // accepts connections from 2 players
    public void SetUp()
    {
        DisplayMessage("Waiting for players...\r\n");

        // set up Socket                                           
        listener =
           new TcpListener(IPAddress.Parse("127.0.0.1"), 50000);
        listener.Start();

        // accept first player and start a player thread              
        players[0] = new Player(listener.AcceptSocket(), this, 0);
        playerThreads[0] =
           new Thread(new ThreadStart(players[0].Run));
        playerThreads[0].Start();

        // accept second player and start another player thread       
        players[1] = new Player(listener.AcceptSocket(), this, 1);
        playerThreads[1] =
           new Thread(new ThreadStart(players[1].Run));
        playerThreads[1].Start();

        // let the first player know that the other player has connected
        lock (players[0])
        {
            players[0].threadSuspended = false;
            Monitor.Pulse(players[0]);
        } // end lock                                                   
    } // end method SetUp
示例#29
0
        // the listener thread's listen function
        // note: no maxConnections parameter. high level API should handle that.
        //       (Transport can't send a 'too full' message anyway)
        void Listen(int port)
        {
            // absolutely must wrap with try/catch, otherwise thread
            // exceptions are silent
            try
            {
                // start listener on all IPv4 and IPv6 address via .Create
                listener = TcpListener.Create(port);
                listener.Server.NoDelay        = NoDelay;
                listener.Server.SendTimeout    = SendTimeout;
                listener.Server.ReceiveTimeout = ReceiveTimeout;
                listener.Start();
                Log.Info("Server: listening port=" + port);

                // keep accepting new clients
                while (true)
                {
                    // wait and accept new client
                    // note: 'using' sucks here because it will try to
                    // dispose after thread was started but we still need it
                    // in the thread
                    TcpClient client = listener.AcceptTcpClient();

                    // set socket options
                    client.NoDelay        = NoDelay;
                    client.SendTimeout    = SendTimeout;
                    client.ReceiveTimeout = ReceiveTimeout;

                    // generate the next connection id (thread safely)
                    int connectionId = NextConnectionId();

                    // add to dict immediately
                    ConnectionState connection = new ConnectionState(client, MaxMessageSize);
                    clients[connectionId] = connection;

                    // spawn a send thread for each client
                    Thread sendThread = new Thread(() =>
                    {
                        // wrap in try-catch, otherwise Thread exceptions
                        // are silent
                        try
                        {
                            // run the send loop
                            // IMPORTANT: DO NOT SHARE STATE ACROSS MULTIPLE THREADS!
                            ThreadFunctions.SendLoop(connectionId, client, connection.sendPipe, connection.sendPending);
                        }
                        catch (ThreadAbortException)
                        {
                            // happens on stop. don't log anything.
                            // (we catch it in SendLoop too, but it still gets
                            //  through to here when aborting. don't show an
                            //  error.)
                        }
                        catch (Exception exception)
                        {
                            Log.Error("Server send thread exception: " + exception);
                        }
                    });
                    sendThread.IsBackground = true;
                    sendThread.Start();

                    // spawn a receive thread for each client
                    Thread receiveThread = new Thread(() =>
                    {
                        // wrap in try-catch, otherwise Thread exceptions
                        // are silent
                        try
                        {
                            // run the receive loop
                            // (receive pipe is shared across all loops)
                            ThreadFunctions.ReceiveLoop(connectionId, client, MaxMessageSize, receivePipe, ReceiveQueueLimit);

                            // IMPORTANT: do NOT remove from clients after the
                            // thread ends. need to do it in Tick() so that the
                            // disconnect event in the pipe is still processed.
                            // (removing client immediately would mean that the
                            //  pipe is lost and the disconnect event is never
                            //  processed)

                            // sendthread might be waiting on ManualResetEvent,
                            // so let's make sure to end it if the connection
                            // closed.
                            // otherwise the send thread would only end if it's
                            // actually sending data while the connection is
                            // closed.
                            sendThread.Interrupt();
                        }
                        catch (Exception exception)
                        {
                            Log.Error("Server client thread exception: " + exception);
                        }
                    });
                    receiveThread.IsBackground = true;
                    receiveThread.Start();
                }
            }
            catch (ThreadAbortException exception)
            {
                // UnityEditor causes AbortException if thread is still
                // running when we press Play again next time. that's okay.
                Log.Info("Server thread aborted. That's okay. " + exception);
            }
            catch (SocketException exception)
            {
                // calling StopServer will interrupt this thread with a
                // 'SocketException: interrupted'. that's okay.
                Log.Info("Server Thread stopped. That's okay. " + exception);
            }
            catch (Exception exception)
            {
                // something went wrong. probably important.
                Log.Error("Server Exception: " + exception);
            }
        }
示例#30
0
        public override void Bad()
        {
            int data;

            if (IO.StaticReturnsTrueOrFalse())
            {
                data = int.MinValue; /* Initialize data */
                /* Read data using a listening tcp connection */
                {
                    TcpListener listener = null;
                    /* Read data using a listening tcp connection */
                    try
                    {
                        listener = new TcpListener(IPAddress.Parse("10.10.1.10"), 39543);
                        listener.Start();
                        using (TcpClient tcpConn = listener.AcceptTcpClient())
                        {
                            /* read input from socket */
                            using (StreamReader sr = new StreamReader(tcpConn.GetStream()))
                            {
                                /* POTENTIAL FLAW: Read data using a listening tcp connection */
                                string stringNumber = sr.ReadLine();
                                if (stringNumber != null) // avoid NPD incidental warnings
                                {
                                    try
                                    {
                                        data = int.Parse(stringNumber.Trim());
                                    }
                                    catch (FormatException exceptNumberFormat)
                                    {
                                        IO.Logger.Log(NLog.LogLevel.Warn, exceptNumberFormat, "Number format exception parsing data from string");
                                    }
                                }
                            }
                        }
                    }
                    catch (IOException exceptIO)
                    {
                        IO.Logger.Log(NLog.LogLevel.Warn, exceptIO, "Error with stream reading");
                    }
                    finally
                    {
                        try
                        {
                            if (listener != null)
                            {
                                listener.Stop();
                            }
                        }
                        catch (SocketException se)
                        {
                            IO.Logger.Log(NLog.LogLevel.Warn, se, "Error closing TcpListener");
                        }
                    }
                }
            }
            else
            {
                /* FIX: Use a hardcoded number that won't cause underflow, overflow, divide by zero, or loss-of-precision issues */
                data = 2;
            }
            if (IO.StaticReturnsTrueOrFalse())
            {
                /* POTENTIAL FLAW: Zero modulus will cause an issue.  An integer division will
                 * result in an exception.  */
                IO.WriteLine("100%" + data + " = " + (100 % data) + "\n");
            }
            else
            {
                /* FIX: test for a zero modulus */
                if (data != 0)
                {
                    IO.WriteLine("100%" + data + " = " + (100 % data) + "\n");
                }
                else
                {
                    IO.WriteLine("This would result in a modulo by zero");
                }
            }
        }
示例#31
0
        /// <summary>
        /// 接受连接的回调函数
        /// </summary>
        /// <param name="ar"></param>
        private void AcceptSocketCallback(IAsyncResult ar)
        {
            TcpListener tcpListener = ar.AsyncState as TcpListener;

            Socket serverSocket = null;

            bool bError = true;;

            try
            {
                serverSocket = tcpListener.EndAcceptSocket(ar);

                bError = false;
            }
            catch (SocketException sex)
            {
                Debug.WriteLine(string.Format("AsyncTcpServer_AcceptSocket_SocketException:{0}", sex.StackTrace));
                OnError(string.Format("AsyncTcpServer_AcceptSocket_SocketException:{0}", sex.StackTrace), null);
            }
            catch (ObjectDisposedException oex)
            {
                Debug.WriteLine(string.Format("AsyncTcpServer_AcceptSocket_ObjectDisposedException:{0}", oex.StackTrace));
                OnError(string.Format("AsyncTcpServer_AcceptSocket_ObjectDisposedException:{0}", oex.StackTrace), null);
            }
            catch (Exception ex)
            {
                Debug.WriteLine(string.Format("AsyncTcpServer_AcceptSocket_Exception:{0}", ex.StackTrace));
                OnError(string.Format("AsyncTcpServer_AcceptSocket_Exception:{0}", ex.StackTrace), null);
            }



            Debug.WriteLine(string.Format("当前连接数:{0}", this._connectedServerSockets.Count));

            try
            {
                // 接受新连接
                tcpListener.BeginAcceptSocket(new AsyncCallback(this.AcceptSocketCallback), tcpListener);
            }
            catch (Exception exAcceptNew)
            {
                Debug.WriteLine(string.Format("接收新套接字时出错:{0}", exAcceptNew.StackTrace));
                OnError(string.Format("接收新套接字时出错:{0}", exAcceptNew.StackTrace), null);
            }

            if (bError)
            {
                return;
            }

            TcpServerSocket socketWrapper = new TcpServerSocket(serverSocket);

            //////////////socketWrapper.ProtocolReceiver.OnProtocolReceived += new RoutedPropertyChangedEventHandler<protocol>(ProtocolReceiver_OnProtocolReceived);

            // 加入连接列表
            this.AddSocketToList(socketWrapper);
            // 调用事件
            if (this.OnAcceptSocket != null)
            {
                this.OnAcceptSocket(this, new TcpServerEventArgs(socketWrapper));
            }

            bError = true;

            try
            {
                // 开始接收数据
                serverSocket.BeginReceive(socketWrapper.Buffer, 0, socketWrapper.Buffer.Length, SocketFlags.None, new AsyncCallback(this.ReceiveDataCallback), socketWrapper);

                bError = false;
            }
            catch (SocketException sex1)
            {
                Debug.WriteLine(string.Format("AsyncTcpServer_AcceptSocket_BeginReceive_SocketException:{0}", sex1.StackTrace));
                OnError(string.Format("AsyncTcpServer_AcceptSocket_BeginReceive_SocketException:{0}", sex1.StackTrace), null);
            }
            catch (ObjectDisposedException oex1)
            {
                Debug.WriteLine(string.Format("AsyncTcpServer_AcceptSocket_BeginReceive_ObjectDisposedException:{0}", oex1.StackTrace));
                OnError(string.Format("AsyncTcpServer_AcceptSocket_BeginReceive_ObjectDisposedException:{0}", oex1.StackTrace), null);
            }
            catch (Exception ex1)
            {
                Debug.WriteLine(string.Format("AsyncTcpServer_AcceptSocket_BeginReceive_Exception:{0}", ex1.StackTrace));
                OnError(string.Format("AsyncTcpServer_AcceptSocket_BeginReceive_Exception:{0}", ex1.StackTrace), null);
            }

            if (bError)
            {
                try
                {
                    //serverSocket.Shutdown(SocketShutdown.Both);
                    serverSocket.Close();

                    if (this.OnClientDisconnected != null)
                    {
                        this.OnClientDisconnected(this, new TcpServerEventArgs(serverSocket));
                    }
                }
                catch (Exception ex)
                {
                    Debug.WriteLine(string.Format("关闭客户端连接出错:{0}", ex.StackTrace));
                    OnError(string.Format("关闭客户端连接出错:{0}", ex.StackTrace), null);
                }

                // 从列表中删除
                this.RemoveSocketFromList(socketWrapper);
            }


            // 清理引用
            serverSocket  = null;
            socketWrapper = null;
        }
        /* goodB2G1() - use badsource and goodsink by changing second privateFive==5 to privateFive!=5 */
        private void GoodB2G1(HttpRequest req, HttpResponse resp)
        {
            string data;

            if (privateFive == 5)
            {
                data = ""; /* Initialize data */
                /* Read data using a listening tcp connection */
                {
                    TcpListener listener = null;
                    try
                    {
                        listener = new TcpListener(IPAddress.Parse("10.10.1.10"), 39543);
                        listener.Start();
                        using (TcpClient tcpConn = listener.AcceptTcpClient())
                        {
                            /* read input from socket */
                            using (StreamReader sr = new StreamReader(tcpConn.GetStream()))
                            {
                                /* POTENTIAL FLAW: Read data using a listening tcp connection */
                                data = sr.ReadLine();
                            }
                        }
                    }
                    catch (IOException exceptIO)
                    {
                        IO.Logger.Log(NLog.LogLevel.Warn, exceptIO, "Error with stream reading");
                    }
                    finally
                    {
                        if (listener != null)
                        {
                            try
                            {
                                listener.Stop();
                            }
                            catch (SocketException se)
                            {
                                IO.Logger.Log(NLog.LogLevel.Warn, se, "Error closing TcpListener");
                            }
                        }
                    }
                }
            }
            else
            {
                /* INCIDENTAL: CWE 561 Dead Code, the code below will never run
                 * but ensure data is inititialized before the Sink to avoid compiler errors */
                data = null;
            }
            if (privateFive != 5)
            {
                /* INCIDENTAL: CWE 561 Dead Code, the code below will never run */
                IO.WriteLine("Benign, fixed string");
            }
            else
            {
                /* FIX: use URLEncoder.encode to hex-encode non-alphanumerics */
                if (data != null)
                {
                    data = HttpUtility.UrlEncode("", Encoding.UTF8);
                    resp.AddHeader("Location", "/author.jsp?lang=" + data);
                }
            }
        }
        public override void Bad()
        {
            int data;

            /* We need to have one source outside of a for loop in order
             * to prevent the compiler from generating an error because
             * data is uninitialized
             */
            data = int.MinValue; /* Initialize data */
            /* Read data using a listening tcp connection */
            {
                TcpListener listener = null;
                /* Read data using a listening tcp connection */
                try
                {
                    listener = new TcpListener(IPAddress.Parse("10.10.1.10"), 39543);
                    listener.Start();
                    using (TcpClient tcpConn = listener.AcceptTcpClient())
                    {
                        /* read input from socket */
                        using (StreamReader sr = new StreamReader(tcpConn.GetStream()))
                        {
                            /* POTENTIAL FLAW: Read data using a listening tcp connection */
                            string stringNumber = sr.ReadLine();
                            if (stringNumber != null) // avoid NPD incidental warnings
                            {
                                try
                                {
                                    data = int.Parse(stringNumber.Trim());
                                }
                                catch (FormatException exceptNumberFormat)
                                {
                                    IO.Logger.Log(NLog.LogLevel.Warn, exceptNumberFormat, "Number format exception parsing data from string");
                                }
                            }
                        }
                    }
                }
                catch (IOException exceptIO)
                {
                    IO.Logger.Log(NLog.LogLevel.Warn, exceptIO, "Error with stream reading");
                }
                finally
                {
                    try
                    {
                        if (listener != null)
                        {
                            listener.Stop();
                        }
                    }
                    catch (SocketException se)
                    {
                        IO.Logger.Log(NLog.LogLevel.Warn, se, "Error closing TcpListener");
                    }
                }
            }
            for (int j = 0; j < 1; j++)
            {
                /* POTENTIAL FLAW: Zero denominator will cause an issue.  An integer division will
                 * result in an exception. */
                IO.WriteLine("bad: 100/" + data + " = " + (100 / data) + "\n");
            }
        }
示例#34
0
        public static void Connect()
        {
            server = null;
            try
            {
                // Set the TcpListener on port 13000.
                Int32 port = 13000;

                // TcpListener server = new TcpListener(port);
                server = new TcpListener(IPAddress.Loopback, port);

                // Start listening for client requests.
                server.Start();

                // Buffer for reading data
                Byte[] bytes = new Byte[256];
                String data  = null;

                // Enter the listening loop.
                while (true)
                {
                    Console.Write("Waiting for a connection... ");

                    // Perform a blocking call to accept requests.
                    // You could also use server.AcceptSocket() here.
                    client = server.AcceptTcpClient();
                    Console.WriteLine("Connected!");

                    data = null;

                    // Get a stream object for reading and writing
                    NetworkStream stream = client.GetStream();

                    int i;

                    // Loop to receive all the data sent by the client.
                    while ((i = stream.Read(bytes, 0, bytes.Length)) != 0)
                    {
                        // Translate data bytes to a ASCII string.
                        data = System.Text.Encoding.ASCII.GetString(bytes, 0, i);
                        Console.WriteLine("Received: {0}", data);
                        Decode(data);
                        // Process the data sent by the client.

                        // Dont write anything back
                        //data = data.ToUpper();
                        //byte[] msg = System.Text.Encoding.ASCII.GetBytes(data);
                        //// Send back a response.
                        //stream.Write(msg, 0, msg.Length);
                        //Console.WriteLine("Sent: {0}", data);
                    }
                    //stream.Close();//Maybe?
                    // Shutdown and end connection
                    //client.Close();
                }
            }
            catch (Exception ex)
            {
                LogExceptions(ex.ToString());
            }
            //finally
            //{
            //    // stop listening for new clients.
            //    //server.Stop();
            //}

            //Console.WriteLine("\nHit enter to continue...");
            //Console.Read();
        }
示例#35
0
        /// <summary>
        /// Start a IMAP proxy instance.
        /// </summary>
        /// <param name="acceptedIPs">IP addresses to accept connections from.</param>
        /// <param name="localIPAddress">Local IP address to bind to.</param>
        /// <param name="localPort">Local port to listen on.</param>
        /// <param name="localEnableSsl">Whether the local server supports TLS/SSL.</param>
        /// <param name="remoteServerHostName">Remote server hostname to forward all IMAP messages to.</param>
        /// <param name="remoteServerPort">Remote server port to connect to.</param>
        /// <param name="remoteServerEnableSsl">Whether the remote IMAP server requires TLS/SSL.</param>
        /// <param name="remoteServerCredential">(Optional) Credentials to be used for all connections to the remote IMAP server.  When set, this overrides any credentials passed locally.</param>
        /// <param name="exportDirectory">(Optional) Location where all incoming messages are saved as EML files.</param>
        /// <param name="logFile">File where event logs and exception information will be written.</param>
        /// <param name="logLevel">Proxy logging level, determining how much information is logged.</param>
        /// <param name="instanceId">The instance number of the proxy.</param>
        /// <param name="debugMode">Whether the proxy instance is running in DEBUG mode and should output full exception messages.</param>
        public void Start(string acceptedIPs, IPAddress localIPAddress, int localPort, bool localEnableSsl, string remoteServerHostName, int remoteServerPort, bool remoteServerEnableSsl, NetworkCredential remoteServerCredential, string exportDirectory, string logFile, LogLevel logLevel, int instanceId, bool debugMode)
        {
            // Create the log writer.
            string logFileName = "";

            if (!string.IsNullOrEmpty(logFile))
            {
                logFileName         = ProxyFunctions.GetLogFileName(logFile, instanceId, localIPAddress.ToString(), remoteServerHostName, localPort, remoteServerPort);
                LogWriter           = new StreamWriter(logFileName, true, Encoding.UTF8, Constants.SMALLBUFFERSIZE);
                LogWriter.AutoFlush = true;

                LogLevel = logLevel;
            }

            // Make sure the remote server isn't an infinite loop back to this server.
            string fqdn = Functions.GetLocalFQDN();

            if (remoteServerHostName.ToUpper() == fqdn.ToUpper() && remoteServerPort == localPort)
            {
                ProxyFunctions.Log(LogWriter, SessionId, "Cannot start service because the remote server host name {" + remoteServerHostName + "} and port {" + remoteServerPort.ToString() + "} is the same as this proxy, which would cause an infinite loop.", Proxy.LogLevel.Critical, LogLevel);
                return;
            }
            IPHostEntry hostEntry = Dns.GetHostEntry(Dns.GetHostName());

            foreach (IPAddress hostIP in hostEntry.AddressList)
            {
                if (remoteServerHostName == hostIP.ToString() && remoteServerPort == localPort)
                {
                    ProxyFunctions.Log(LogWriter, SessionId, "Cannot start service because the remote server hostname {" + remoteServerHostName + "} and port {" + remoteServerPort.ToString() + "} is the same as this proxy, which would cause an infinite loop.", Proxy.LogLevel.Critical, LogLevel);
                    return;
                }
            }

            ProxyFunctions.Log(LogWriter, SessionId, "Starting service.", Proxy.LogLevel.Information, LogLevel);

            // Attempt to start up to 3 times in case another service using the port is shutting down.
            int startAttempts = 0;

            while (startAttempts < 3)
            {
                startAttempts++;

                // If we've failed to start once, wait an extra 10 seconds.
                if (startAttempts > 1)
                {
                    ProxyFunctions.Log(LogWriter, SessionId, "Attempting to start for the " + (startAttempts == 2 ? "2nd" : "3rd") + " time.", Proxy.LogLevel.Information, LogLevel);
                    Thread.Sleep(10000 * startAttempts);
                }

                try
                {
                    X509Certificate serverCertificate = null;

                    // Generate a unique session ID for logging.
                    SessionId    = Guid.NewGuid().ToString();
                    ConnectionId = 0;

                    // If local SSL is supported via STARTTLS, ensure we have a valid server certificate.
                    if (localEnableSsl)
                    {
                        serverCertificate = CertHelper.GetCertificateBySubjectName(StoreLocation.LocalMachine, fqdn);
                        // In case the service as running as the current user, check the Current User certificate store as well.
                        if (serverCertificate == null)
                        {
                            serverCertificate = CertHelper.GetCertificateBySubjectName(StoreLocation.CurrentUser, fqdn);
                        }

                        // If no certificate was found, generate a self-signed certificate.
                        if (serverCertificate == null)
                        {
                            ProxyFunctions.Log(LogWriter, SessionId, "No signing certificate found, so generating new certificate.", Proxy.LogLevel.Warning, LogLevel);

                            List <string> oids = new List <string>();
                            oids.Add("1.3.6.1.5.5.7.3.1");    // Server Authentication.

                            // Generate the certificate with a duration of 10 years, 4096-bits, and a key usage of server authentication.
                            serverCertificate = CertHelper.CreateSelfSignedCertificate(fqdn, fqdn, StoreLocation.LocalMachine, true, 4096, 10, oids);

                            ProxyFunctions.Log(LogWriter, SessionId, "Certificate generated with Serial Number {" + serverCertificate.GetSerialNumberString() + "}.", Proxy.LogLevel.Information, LogLevel);
                        }
                    }

                    Listener = new TcpListener(localIPAddress, localPort);
                    Listener.Start();

                    ProxyFunctions.Log(LogWriter, SessionId, "Service started.", Proxy.LogLevel.Information, LogLevel);
                    ProxyFunctions.Log(LogWriter, SessionId, "Listening on address {" + localIPAddress.ToString() + "}, port {" + localPort + "}.", Proxy.LogLevel.Information, LogLevel);

                    Started = true;

                    // Accept client requests, forking each into its own thread.
                    while (Started)
                    {
                        TcpClient client = Listener.AcceptTcpClient();

                        string newLogFileName = ProxyFunctions.GetLogFileName(logFile, instanceId, localIPAddress.ToString(), remoteServerHostName, localPort, remoteServerPort);
                        if (newLogFileName != logFileName)
                        {
                            LogWriter.Close();
                            LogWriter           = new StreamWriter(newLogFileName, true, Encoding.UTF8, Constants.SMALLBUFFERSIZE);
                            LogWriter.AutoFlush = true;
                        }

                        // Prepare the arguments for our new thread.
                        ImapProxyConnectionArguments arguments = new ImapProxyConnectionArguments();
                        arguments.AcceptedIPs            = acceptedIPs;
                        arguments.TcpClient              = client;
                        arguments.Certificate            = serverCertificate;
                        arguments.ExportDirectory        = exportDirectory;
                        arguments.LocalIpAddress         = localIPAddress;
                        arguments.LocalPort              = localPort;
                        arguments.LocalEnableSsl         = localEnableSsl;
                        arguments.RemoteServerHostName   = remoteServerHostName;
                        arguments.RemoteServerPort       = remoteServerPort;
                        arguments.RemoteServerEnableSsl  = remoteServerEnableSsl;
                        arguments.RemoteServerCredential = remoteServerCredential;

                        // Increment the connection counter;
                        arguments.ConnectionId = (unchecked (++ConnectionId)).ToString();
                        arguments.InstanceId   = instanceId;
                        arguments.DebugMode    = debugMode;

                        // Fork the thread and continue listening for new connections.
                        Thread processThread = new Thread(new ParameterizedThreadStart(ProcessConnection));
                        processThread.Name = "OpaqueMail IMAP Proxy Connection";
                        processThread.Start(arguments);
                    }
                    return;
                }
                catch (Exception ex)
                {
                    if (debugMode || System.Diagnostics.Debugger.IsAttached)
                    {
                        ProxyFunctions.Log(LogWriter, SessionId, "Exception when starting proxy: " + ex.ToString(), Proxy.LogLevel.Critical, LogLevel);
                    }
                    else
                    {
                        ProxyFunctions.Log(LogWriter, SessionId, "Exception when starting proxy: " + ex.Message, Proxy.LogLevel.Critical, LogLevel);
                    }
                }
            }
        }
示例#36
0
文件: Programm.cs 项目: xjoki/repocs
        static void Main(string[] args)
        {
            WebServer www = new WebServer(80, "c:\\www", "index.htm");

            Console.WriteLine("WebServer wird gestartet...");
            string      ipAddress = "127.0.0.1";
            IPAddress   ip        = IPAddress.Parse(ipAddress);
            IPEndPoint  ep        = new IPEndPoint(ip, www.Port);
            TcpListener listen    = null;

            // Datenpuffer
            Byte[] bytes = null;
            int    i;

            try
            {
                listen = new TcpListener(ep);
                listen.Start();
            }
            catch (Exception)
            {
                throw;
            }

            do
            {
                Console.WriteLine("Warte auf eine Verbindung...");
                TcpClient client = listen.AcceptTcpClient();
                Console.WriteLine("Verbindung hergestellt!");
                string        Data   = null;
                NetworkStream stream = client.GetStream();
                bytes = new Byte[client.ReceiveBufferSize];

                Console.WriteLine("Client-Anfrage...");
                // Lesen der Daten

                i = stream.Read(bytes, 0, bytes.Length);
                if (i > 0)
                {
                    Data = System.Text.Encoding.ASCII.GetString(bytes, 0, i);
                    Console.WriteLine(Data);
                }
                // Tokens
                string[] words = Data.Split(' ');
                if (words[0] == "GET")
                {
                    if (words[1].EndsWith("/"))
                    {
                        words[1] = words[1] + www.DefaultFile;
                    }

                    // Dokument an Client senden
                    FileStream file = null;
                    try
                    {
                        file = new FileStream(www.DocumentRoot + words[1], FileMode.Open);
                        byte[] readBuffer = new byte[4096];
                        int    r          = 0;
                        int    offset     = 0;
                        while ((r = file.Read(readBuffer, offset, readBuffer.Length)) > 0)
                        {
                            stream.Write(readBuffer, 0, r);
                        }
                    }
                    catch (FileNotFoundException)
                    {
                        string errMsg =
                            "<html><head><title>Fehler</title></head>" +
                            "<body><h2>404 Nicht gefunden</h2></body></html>";

                        ASCIIEncoding enc = new ASCIIEncoding();
                        stream.Write(enc.GetBytes(errMsg), 0, errMsg.Length);
                    }
                    catch (Exception)
                    {
                        throw;
                    }
                    finally
                    {
                        if (file != null)
                        {
                            file.Close();
                        }
                    }
                }
                else
                {
                    Console.WriteLine("FEHLER 400 : BAD REQUEST");
                }
                client.Close();
                i = 0;
            } while (true);
        }
示例#37
0
        private static void Main()
        {
            Console.Title       = "Zteam Studio GameServer";
            LogFactory.OnWrite += Log.LogFactory_ConsoleWrite;
start:
            try
            {
                Settings.Initialize();

                AutoRestartTIme = Settings.GetInt("GameServer/AutoRestartTime");
                LogFactory.GetLog("Main").LogInfo("reinicializaçao automatica do servidor é definido como {0} segundos.", Server.AutoRestartTIme);

                UDPRelayIP    = Settings.GetString("GameServer/UDPRelayIP");
                UDPRelayPort  = Settings.GetShort("GameServer/UDPRelayPort");
                TCPRelayIP    = Settings.GetString("GameServer/TCPRelayIP");
                TCPRelayPort  = Settings.GetShort("GameServer/TCPRelayPort");
                MsgServerIP   = Settings.GetString("GameServer/MsgServerIP");
                MsgServerPort = Settings.GetShort("GameServer/MsgServerPort");

                TSingleton <ChannelManager> .Instance.AddChannel("대전", 2000, 0);

                TSingleton <ChannelManager> .Instance.AddChannel("던전", 2000, 0);

                Clients = new GCClients();
                LogFactory.GetLog("Main").LogInfo("Criando lista de clientes objetos");

                Handlers = new HandlerStore <GCClient>();
                Handlers.Cache();

                Database.Test();
                Database.Analyze();

                LogFactory.GetLog("Shop").LogInfo("Carregando Items da DB");
                Shop shop = new Shop();

                shop.LoadShop();
                LogFactory.GetLog("Shop").LogInfo("Items Carregads, Total: " + shop.goodsIttems.Length);

                LogFactory.GetLog("Hero Dungeon").LogInfo("Carregando Lista De Hero!");

                GCCommon MyCommon = new GCCommon();

                MyCommon.LoadHero();
                LogFactory.GetLog("Hero Dungeon").LogInfo("Hero Dungeon Carreda!,Total: " + MyCommon.herodungeon.Length);

                RemoteEndPoint = new IPEndPoint(Settings.GetIPAddress("GameServer/ExternalIP"), Settings.GetInt("GameServer/Port"));

                Listener = new TcpListener(IPAddress.Any, Server.RemoteEndPoint.Port);
                Listener.Start();
                LogFactory.GetLog("Main").LogInfo("conexao socket iniciada. porta: {0}.", Server.Listener.LocalEndpoint);

                User.StatusOnline(null, null, 0, 2);

                IsAlive = true;
            }
            catch (Exception e)
            {
                LogFactory.GetLog("MAIN").LogFatal(e);
            }

            if (Server.IsAlive)
            {
                LogFactory.GetLog("Main").LogInfo("o servidor foi aberto com sucesso. a identificaçao do segmento : {0}.", Thread.CurrentThread.ManagedThreadId);
            }
            else
            {
                LogFactory.GetLog("Main").LogInfo("o servidor nao foi iniciado com sucesso.");
            }

            while (Server.IsAlive)
            {
                Server.AcceptDone.Reset();

                Server.Listener.BeginAcceptSocket(new AsyncCallback(Server.OnAcceptSocket), null);

                Server.AcceptDone.WaitOne();
            }

            GCClient[] remainingClients = Server.Clients.ToArray();

            foreach (GCClient client in remainingClients)
            {
                client.Close();
            }

            Server.Dispose();

            LogFactory.GetLog("Main").LogWarning("Error ");

            if (Server.AutoRestartTIme > 0)
            {
                Thread.Sleep(Server.AutoRestartTIme * 1000);

                goto start;
            }
            else
            {
                Console.Read();
            }
            {
                return;
            }
        }
 public HttpServer()
 {
     this.tcpListener = new TcpListener(IPAddress.Parse("127.0.0.1"), 80);
 }
示例#39
0
        // the listener thread's listen function
        private void Listen(int port, int maxConnections)
        {
            // absolutely must wrap with try/catch, otherwise thread
            // exceptions are silent
            try
            {
                // start listener
                // (NoDelay disables nagle algorithm. lowers CPU% and latency)
                _listener = new TcpListener(new IPEndPoint(IPAddress.Any, port));
                _listener.Server.NoDelay = true;
                _listener.Start();
                Logger.Log("Server: listening port=" + port + " max=" + maxConnections);

                // keep accepting new clients
                while (true)
                {
                    // wait and accept new client
                    // note: 'using' sucks here because it will try to
                    // dispose after thread was started but we still need it
                    // in the thread
                    TcpClient client = _listener.AcceptTcpClient();

                    // are more connections allowed?
                    if (_clients.Count < maxConnections)
                    {
                        // generate the next connection id (thread safely)
                        int connectionId = NextConnectionId();

                        // spawn a thread for each client to listen to his
                        // messages
                        Thread thread = new Thread(() =>
                        {
                            // add to dict immediately
                            _clients.Add(connectionId, client);

                            // run the receive loop
                            ReceiveLoop(connectionId, client, MessageQueue);

                            // remove client from clients dict afterwards
                            _clients.Remove(connectionId);
                        });
                        thread.IsBackground = true;
                        thread.Start();
                    }
                    // connection limit reached. disconnect the client and show
                    // a small log message so we know why it happened.
                    // note: no extra Sleep because Accept is blocking anyway
                    else
                    {
                        client.Close();
                        Logger.Log("Server too full, disconnected a client");
                    }
                }
            }
            catch (ThreadAbortException exception)
            {
                // UnityEditor causes AbortException if thread is still
                // running when we press Play again next time. that's okay.
                Logger.Log("Server thread aborted. That's okay. " + exception);
            }
            catch (SocketException exception)
            {
                // calling StopServer will interrupt this thread with a
                // 'SocketException: interrupted'. that's okay.
                Logger.Log("Server Thread stopped. That's okay. " + exception);
            }
            catch (Exception exception)
            {
                // something went wrong. probably important.
                Logger.LogError("Server Exception: " + exception);
            }
        }
示例#40
0
 public Server(int Port)
 {
     ipAddr   = new IPEndPoint(IPAddress.Parse(GetLocalIP), Port);
     listener = new TcpListener(ipAddr);
 }
        public override void Bad()
        {
            int data;

            if (privateFive == 5)
            {
                data = int.MinValue; /* Initialize data */
                /* Read data using a listening tcp connection */
                {
                    TcpListener listener = null;
                    /* Read data using a listening tcp connection */
                    try
                    {
                        listener = new TcpListener(IPAddress.Parse("10.10.1.10"), 39543);
                        listener.Start();
                        using (TcpClient tcpConn = listener.AcceptTcpClient())
                        {
                            /* read input from socket */
                            using (StreamReader sr = new StreamReader(tcpConn.GetStream()))
                            {
                                /* POTENTIAL FLAW: Read data using a listening tcp connection */
                                string stringNumber = sr.ReadLine();
                                if (stringNumber != null) // avoid NPD incidental warnings
                                {
                                    try
                                    {
                                        data = int.Parse(stringNumber.Trim());
                                    }
                                    catch (FormatException exceptNumberFormat)
                                    {
                                        IO.Logger.Log(NLog.LogLevel.Warn, exceptNumberFormat, "Number format exception parsing data from string");
                                    }
                                }
                            }
                        }
                    }
                    catch (IOException exceptIO)
                    {
                        IO.Logger.Log(NLog.LogLevel.Warn, exceptIO, "Error with stream reading");
                    }
                    finally
                    {
                        try
                        {
                            if (listener != null)
                            {
                                listener.Stop();
                            }
                        }
                        catch (SocketException se)
                        {
                            IO.Logger.Log(NLog.LogLevel.Warn, se, "Error closing TcpListener");
                        }
                    }
                }
            }
            else
            {
                /* INCIDENTAL: CWE 561 Dead Code, the code below will never run
                 * but ensure data is inititialized before the Sink to avoid compiler errors */
                data = 0;
            }
            if (privateFive == 5)
            {
                /* POTENTIAL FLAW: Zero modulus will cause an issue.  An integer division will
                 * result in an exception.  */
                IO.WriteLine("100%" + data + " = " + (100 % data) + "\n");
            }
        }
 public SUTControlListener()
 {
     listenServer  = new TcpListener(GetLocalIP(), listenPort);
     processThread = new Thread(new ThreadStart(ProcessControlCommandThread));
 }
示例#43
0
 public ThreadInPool(TcpListener listener, ILogger logger, Func <string, string> workload)
 {
     this.listener = listener;
     this.logger   = logger;
     this.workload = workload;
 }
 public Listener(IPAddress ip, int port)
 {
     _listener = new TcpListener(ip, port);
 }
示例#45
0
        static void Main(string[] args)
        {
            TcpListener server = null;

            try
            {
                // Set the TcpListener on port 13000.
                Int32     port      = 13000;
                IPAddress localAddr = IPAddress.Parse("0.0.0.0");

                // TcpListener server = new TcpListener(port);
                server = new TcpListener(localAddr, port);

                // Start listening for client requests.
                server.Start();

                // Buffer for reading data
                Byte[] bytes = new Byte[256];
                String data  = null;

                // Enter the listening loop.
                while (true)
                {
                    Console.Write("Waiting for a connection... ");

                    // Perform a blocking call to accept requests.
                    // You could also user server.AcceptSocket() here.
                    TcpClient client = server.AcceptTcpClient();
                    Console.WriteLine("Connected!");

                    data = null;

                    // Get a stream object for reading and writing
                    NetworkStream stream = client.GetStream();

                    int i;

                    // Loop to receive all the data sent by the client.
                    while ((i = stream.Read(bytes, 0, bytes.Length)) != 0)
                    {
                        // Translate data bytes to a ASCII string.
                        data = System.Text.Encoding.ASCII.GetString(bytes, 0, i);
                        Console.WriteLine("Received: {0}", data);

                        // Process the data sent by the client.
                        data = data.ToUpper();

                        byte[] msg = System.Text.Encoding.ASCII.GetBytes(data);

                        // Send back a response.
                        //stream.Write(msg, 0, msg.Length);
                        //Console.WriteLine("Sent: {0}", data);
                    }

                    // Shutdown and end connection
                    client.Close();
                }
            }
            catch (SocketException e)
            {
                Console.WriteLine("SocketException: {0}", e);
            }
            finally
            {
                // Stop listening for new clients.
                server.Stop();
            }


            Console.WriteLine("\nHit enter to continue...");
            Console.Read();
        }
示例#46
0
        public override void Bad()
        {
            float data;

            data = float.MinValue; /* Initialize data */
            /* Read data using a listening tcp connection */
            {
                TcpListener  listener = null;
                TcpClient    tcpConn  = null;
                StreamReader sr       = null;
                /* Read data using a listening tcp connection */
                try
                {
                    listener = new TcpListener(IPAddress.Parse("10.10.1.10"), 39543);
                    tcpConn  = listener.AcceptTcpClient();
                    /* read input from socket */
                    sr = new StreamReader(tcpConn.GetStream());
                    /* FLAW: Read data using a listening tcp connection */
                    string stringNumber = sr.ReadLine();
                    if (stringNumber != null) // avoid NPD incidental warnings
                    {
                        try
                        {
                            data = float.Parse(stringNumber.Trim());
                        }
                        catch (FormatException exceptNumberFormat)
                        {
                            IO.Logger.Log(NLog.LogLevel.Warn, exceptNumberFormat, "Number format exception parsing data from string");
                        }
                    }
                }
                catch (IOException exceptIO)
                {
                    IO.Logger.Log(NLog.LogLevel.Warn, exceptIO, "Error with stream reading");
                }
                finally
                {
                    /* Close stream reading objects */
                    try
                    {
                        if (sr != null)
                        {
                            sr.Close();
                        }
                    }
                    catch (IOException exceptIO)
                    {
                        IO.Logger.Log(NLog.LogLevel.Warn, exceptIO, "Error closing StreamReader");
                    }

                    /* Close socket objects */
                    try
                    {
                        if (tcpConn != null)
                        {
                            tcpConn.Close();
                        }
                    }
                    catch (IOException exceptIO)
                    {
                        IO.Logger.Log(NLog.LogLevel.Warn, exceptIO, "Error closing TcpClient");
                    }

                    try
                    {
                        if (listener != null)
                        {
                            listener.Stop();
                        }
                    }
                    catch (IOException exceptIO)
                    {
                        IO.Logger.Log(NLog.LogLevel.Warn, exceptIO, "Error closing TcpListener");
                    }
                }
            }
            CWE197_Numeric_Truncation_Error__float_listen_tcp_to_byte_53b.BadSink(data);
        }
        static void Main(string[] args)
        {
            int         port     = 8080;
            TcpListener listener = new TcpListener(IPAddress.Any, port);

            try
            {
                listener.Start();
                while (true)
                {
                    Console.WriteLine("Listening...");
                    TcpClient    client      = listener.AcceptTcpClient();
                    StreamReader readStream  = new StreamReader(client.GetStream());
                    StreamWriter writeStream = new StreamWriter(client.GetStream());

                    string message = "";

                    try
                    {
                        string request = readStream.ReadLine();
                        Console.WriteLine(request);
                        string[] tokens = request.Split(' ');
                        string   page   = tokens[1];
                        using (writeStream)
                        {
                            if (page == "/")
                            {
                                writeStream.WriteLine("HTTP/1.0 200 OK\n");
                                message = "<!doctype html> <html> <head> <title>Home Page</title> </head> <body> <h1>Welcome to our test page.</h1> <h4>You can check the server information <a href=\"/info\">here</a></h4> </body> </html>";
                                writeStream.Write(message);
                            }
                            else if (page == "/info")
                            {
                                writeStream.WriteLine("HTTP/1.0 200 OK\n");
                                var ci = new CultureInfo("en-US");

                                message = string.Format("<!doctype html> <html> <head> <title>Info Page</title> </head> <body> <h2>Current Time: {0}</h2> <h2>Logical Processors: {1}</h2><h4>Back to the <a href=\"/\">homepage</a></h4> </body> </html>", DateTime.Now.ToString("dd MMM yyyy HH:mm:ss", ci), Environment.ProcessorCount);
                                writeStream.Write(message);
                            }
                            else
                            {
                                writeStream.WriteLine("HTTP/1.0 200 OK\n");
                                message = string.Format("<!doctype html> <html> <head> <title>Error Page</title> </head> <body> <h2 style=\"color: red\">Error! Try going to the <a href=\" / \">home page</a></h2> </body> </html>");
                                writeStream.Write(message);
                            }
                        }
                    }
                    catch (Exception e)
                    {
                        using (writeStream)
                        {
                            writeStream.WriteLine("HTTP/1.0 404 OK\n");
                            Console.WriteLine($"Exception: {e.Message}");
                        }
                    }

                    Console.WriteLine("Response sent.");
                }
            }
            catch (WebException exception)
            {
                Console.WriteLine(exception.Status);
            }
        }
示例#48
0
文件: Server.cs 项目: ivanyanev/SIS
 public Server(int port, ServerRoutingTable serverRoutingTable)
 {
     this.Port               = port;
     this.Listener           = new TcpListener(IPAddress.Parse(LocalHostIpAddress), port);
     this.ServerRoutingTable = serverRoutingTable;
 }
示例#49
0
        public static void Main(string[] args)
        {
            TcpListener server = null;

            try
            {
                // Set the TcpListener on port 13000.
                IPAddress localAddr = IPAddress.Parse(args[0]);

                Int32 port = Convert.ToInt32(args[1]);


                // TcpListener server = new TcpListener(port);
                server = new TcpListener(localAddr, port);

                // Start listening for client requests.
                server.Start();

                // String data = null;

                // Enter the listening loop.
                while (true)
                {
                    Console.Write("Waiting for a connection... ");
                    TcpClient client1 = server.AcceptTcpClient();
                    Console.WriteLine("Connected!");
                    NetworkStream stream1 = client1.GetStream();
                    // StreamReader reader1 = new StreamReader(stream1);
                    // StreamWriter writer1 = new StreamWriter(stream1);

                    Console.Write("Waiting for a connection... ");
                    TcpClient client2 = server.AcceptTcpClient();
                    Console.WriteLine("Connected!");
                    NetworkStream stream2 = client2.GetStream();
                    // StreamReader reader2 = new StreamReader(stream2);
                    // StreamWriter writer2 = new StreamWriter(stream2);

                    TicTac tictac = new TicTac();
                    tictac.Play(stream1, stream2);

                    // data = null;

                    ///////////// Get a stream object for reading and writing
                    // NetworkStream stream1 = client1.GetStream();
                    // StreamReader reader1 = new StreamReader(stream1);
                    // StreamWriter writer1 = new StreamWriter(stream1);

                    // NetworkStream stream2 = client2.GetStream();
                    // StreamReader reader2 = new StreamReader(stream2);
                    // StreamWriter writer2 = new StreamWriter(stream2);
                    // writer.AutoFlush = true;

                    // Loop to receive all the data sent by the client.
                    // while ((data = reader.ReadLine()) != null)
                    // {

                    //     Console.WriteLine("Received: {0}", data);
                    //     // Process the data sent by the client.
                    //     String response = data.ToUpper();

                    //     // Send back a response.
                    //     writer.WriteLine(response);
                    //     writer.Flush();
                    //     Console.WriteLine("Sent: {0}", response);
                    // }

                    // Shutdown and end connection
                    client1.Close();
                }
            }
            catch (SocketException e)
            {
                Console.WriteLine("SocketException: {0}", e);
            }
            finally
            {
                // Stop listening for new clients.
                server.Stop();
            }

            Console.WriteLine("\nHit enter to continue...");
            Console.Read();
        }
示例#50
0
        /* uses badsource and badsink - see how tools report flaws that don't always occur */
        public override void Bad()
        {
            float data;

            if (IO.StaticReturnsTrueOrFalse())
            {
                data = float.MinValue; /* Initialize data */
                /* Read data using a listening tcp connection */
                {
                    TcpListener  listener = null;
                    TcpClient    tcpConn  = null;
                    StreamReader sr       = null;
                    /* Read data using a listening tcp connection */
                    try
                    {
                        listener = new TcpListener(IPAddress.Parse("10.10.1.10"), 39543);
                        tcpConn  = listener.AcceptTcpClient();
                        /* read input from socket */
                        sr = new StreamReader(tcpConn.GetStream());
                        /* FLAW: Read data using a listening tcp connection */
                        string stringNumber = sr.ReadLine();
                        if (stringNumber != null) // avoid NPD incidental warnings
                        {
                            try
                            {
                                data = float.Parse(stringNumber.Trim());
                            }
                            catch (FormatException exceptNumberFormat)
                            {
                                IO.Logger.Log(NLog.LogLevel.Warn, exceptNumberFormat, "Number format exception parsing data from string");
                            }
                        }
                    }
                    catch (IOException exceptIO)
                    {
                        IO.Logger.Log(NLog.LogLevel.Warn, exceptIO, "Error with stream reading");
                    }
                    finally
                    {
                        /* Close stream reading objects */
                        try
                        {
                            if (sr != null)
                            {
                                sr.Close();
                            }
                        }
                        catch (IOException exceptIO)
                        {
                            IO.Logger.Log(NLog.LogLevel.Warn, exceptIO, "Error closing StreamReader");
                        }

                        /* Close socket objects */
                        try
                        {
                            if (tcpConn != null)
                            {
                                tcpConn.Close();
                            }
                        }
                        catch (IOException exceptIO)
                        {
                            IO.Logger.Log(NLog.LogLevel.Warn, exceptIO, "Error closing TcpClient");
                        }

                        try
                        {
                            if (listener != null)
                            {
                                listener.Stop();
                            }
                        }
                        catch (IOException exceptIO)
                        {
                            IO.Logger.Log(NLog.LogLevel.Warn, exceptIO, "Error closing TcpListener");
                        }
                    }
                }
            }
            else
            {
                /* FIX: Use a hardcoded number that won't cause underflow, overflow, divide by zero, or loss-of-precision issues */
                data = 2;
            }
            {
                /* POTENTIAL FLAW: Convert data to a int, possibly causing a truncation error */
                IO.WriteLine((int)data);
            }
        }
示例#51
0
        // Main thread for sending telegrams
        private void SendThreading()
        {
            TelegramACK telAck = null;

            try
            {
                if (SimulateMFCS)
                {
                    SendListener = new TcpListener(SendIPEndPoint);
                    Log.AddLog(Log.Severity.EVENT, Name, "Communication.SendThreading", SendIPEndPoint.ToString());
                    SendListener.Start();
                }

                lock (_lockSendTelegram)
                {
                    SendTelegrams.RemoveAll(p => p.CommSendStatus >= Telegram.CommSendStatusEnum.Ack);
                }

                LastSendTime = DateTime.Now;

                while (Thread.CurrentThread.ThreadState == ThreadState.Background)
                {
                    try
                    {
                        Telegram tel = null;
                        lock (_lockSendTelegram)
                            tel = SendTelegrams.FirstOrDefault(prop => prop.CommSendStatus < Telegram.CommSendStatusEnum.Ack);
                        if (DateTime.Now - LastSendTime > SendTimeOut)
                        {
                            InitSendSocket();
                            if (tel != null)
                            {
                                tel.CommSendStatus = Telegram.CommSendStatusEnum.None;
                            }
                            LastSendTime = DateTime.Now;
                            Retry        = 0;
                            Log.AddLog(Log.Severity.EVENT, Name, "Communication.SendThread", "Send timeout, SendSocket reinitialized!");
                        }
                        else if (DateTime.Now - LastSendTime > KeepALifeTime && tel == null)
                        {
                            Telegram tRes = null;
                            lock (_lockSendTelegram)
                                tRes = SendTelegrams.FirstOrDefault(prop => prop.CommSendStatus < Telegram.CommSendStatusEnum.Ack);
                            if (tRes == null)
                            {
                                if (KeepALifeTelegram != null)
                                {
                                    Telegram t = Activator.CreateInstance(KeepALifeTelegram.GetType()) as Telegram;
                                    t.Sender   = MFCS_ID;
                                    t.Receiver = PLC_ID;
                                    t.Build();
                                    AddSendTelegram(t);
                                    Log.AddLog(Log.Severity.EVENT, Name, "Communication.SendThread", String.Format("Adding KeepALife telegram"));
                                }
                            }
                        }
                        else if (!SendSocket.Connected)
                        {
                            InitSendSocket();
                            ConnectSendPartner();
                        }
                        else if (tel != null)
                        {
                            switch (tel.CommSendStatus)
                            {
                            case (Telegram.CommSendStatusEnum.None):
                                tel.Sequence = Sequence;
                                tel.Build();
                                // Log.AddLog(Log.Severity.EVENT, Name, "Communication.SendThread", String.Format("Start sending {0}", tel.ToString()));
                                SendSocket.Send(tel.ByteBuffer, tel.Length, SocketFlags.None);
                                Log.AddLog(Log.Severity.EVENT, Name, "Communication.SendThread", String.Format("Sended {0}", tel.ToString()));
                                tel.CommSendStatus = Telegram.CommSendStatusEnum.WaitACK;
                                telAck             = new TelegramACK();
                                SendTime           = DateTime.Now;
                                break;

                            case (Telegram.CommSendStatusEnum.WaitACK):
                                int numRead = 0;
                                do
                                {
                                    numRead += SendSocket.Receive(telAck.ByteBuffer, numRead, telAck.ByteBuffer.Length - numRead, SocketFlags.None);
                                } while (numRead < telAck.ByteBuffer.Length);
                                telAck.ReadBuffer();
                                Log.AddLog(Log.Severity.EVENT, Name, "Communication.SendThread", String.Format("Received ACK {0}", telAck.ToString()));
                                if (telAck.Validate() && telAck.Sequence == tel.Sequence)
                                {
                                    tel.CommSendStatus = Telegram.CommSendStatusEnum.Ack;
                                    LastSendTime       = DateTime.Now;
                                    Retry = 0;
                                    if (Sequence < 99)
                                    {
                                        Sequence++;
                                    }
                                    else
                                    {
                                        Sequence = 0;
                                    }
                                    Log.AddLog(Log.Severity.EVENT, Name, "Communication.SendThreading", String.Format("Send Finished : {0}", tel.ToString()));
                                    NotifySend(tel);
                                }
                                else
                                {
                                    //                                      tel.CommSendStatus = Telegram.CommSendStatusEnum.None;
                                    Retry++;
                                    Log.AddLog(Log.Severity.EVENT, Name, "Communication.SendThreading", String.Format("Retry increased - {0}", Retry));
                                }
                                break;

                            default:
                                break;
                            }
                        }
                        else
                        {
                            Thread.Sleep(100);
                        }
                    }
                    catch (SocketException ex)
                    {
                        Log.AddLog(Log.Severity.EXCEPTION, Name, "Communication.SendThread::SocketException", ex.Message);
                        Thread.Sleep(1000);
                    }
                }
                catch (TelegramException ex)
                {
                    Log.AddLog(Log.Severity.EXCEPTION, Name, "Communication.SendThread::TelegramException", ex.Message);
                    Thread.Sleep(1000);
                }
                catch (ThreadAbortException ex)
                {
                    Log.AddLog(Log.Severity.EXCEPTION, Name, "Communication.RcvThreading::Communication", ex.Message);
                    return;
                }
                catch (CommunicationException ex)
                {
                    Log.AddLog(Log.Severity.EXCEPTION, Name, "Communication.SendThread::CommunicationException", ex.Message);
                    Thread.Sleep(1000);
                }
            }
示例#52
0
        public void StartListening()
        {
            try
            {
                this.listener = new TcpListener(IPAddress.Any, this.Port);

                this.Prefix             = new Uri(string.Format(CultureInfo.InvariantCulture, "http://localhost:{0}", this.Port));
                this.dispatcher         = new UriDispatchTables(new Uri(this.Prefix, UrnPrefix));
                this.executorDispatcher = new CommandExecutorDispatchTable();

                // Start listening for client requests.
                this.listener.Start();

                // Enter the listening loop
                while (true)
                {
                    Logger.Debug("Waiting for a connection...");

                    // Perform a blocking call to accept requests.
                    var client = this.listener.AcceptTcpClient();

                    // Get a stream object for reading and writing
                    using (var stream = client.GetStream())
                    {
                        var acceptedRequest = HttpRequest.ReadFromStreamWithoutClosing(stream);

                        if (string.IsNullOrWhiteSpace(acceptedRequest.StartingLine))
                        {
                            Logger.Warn("ACCEPTED EMPTY REQUEST");
                        }
                        else
                        {
                            Logger.Debug("ACCEPTED REQUEST {0}", acceptedRequest.StartingLine);

                            var response = this.HandleRequest(acceptedRequest);
                            using (var writer = new StreamWriter(stream))
                            {
                                try
                                {
                                    writer.Write(response);
                                    writer.Flush();
                                }
                                catch (IOException ex)
                                {
                                    Logger.Error("Error occured while writing response: {0}", ex);
                                }
                            }
                        }

                        // Shutdown and end connection
                    }

                    client.Close();

                    Logger.Debug("Client closed\n");
                }
            }
            catch (SocketException ex)
            {
                Logger.Error("SocketException occurred while trying to start listner: {0}", ex);
                throw;
            }
            catch (ArgumentException ex)
            {
                Logger.Error("ArgumentException occurred while trying to start listner: {0}", ex);
                throw;
            }
            finally
            {
                // Stop listening for new clients.
                this.listener.Stop();
            }
        }
        /* goodB2G() - use badsource and goodsink*/
        private void GoodB2G()
        {
            int data;

            data = int.MinValue; /* Initialize data */
            /* Read data using a listening tcp connection */
            {
                TcpListener listener = null;
                /* Read data using a listening tcp connection */
                try
                {
                    listener = new TcpListener(IPAddress.Parse("10.10.1.10"), 39543);
                    listener.Start();
                    using (TcpClient tcpConn = listener.AcceptTcpClient())
                    {
                        /* read input from socket */
                        using (StreamReader sr = new StreamReader(tcpConn.GetStream()))
                        {
                            /* POTENTIAL FLAW: Read data using a listening tcp connection */
                            string stringNumber = sr.ReadLine();
                            if (stringNumber != null) // avoid NPD incidental warnings
                            {
                                try
                                {
                                    data = int.Parse(stringNumber.Trim());
                                }
                                catch (FormatException exceptNumberFormat)
                                {
                                    IO.Logger.Log(NLog.LogLevel.Warn, exceptNumberFormat, "Number format exception parsing data from string");
                                }
                            }
                        }
                    }
                }
                catch (IOException exceptIO)
                {
                    IO.Logger.Log(NLog.LogLevel.Warn, exceptIO, "Error with stream reading");
                }
                finally
                {
                    try
                    {
                        if (listener != null)
                        {
                            listener.Stop();
                        }
                    }
                    catch (SocketException se)
                    {
                        IO.Logger.Log(NLog.LogLevel.Warn, se, "Error closing TcpListener");
                    }
                }
            }
            for (int k = 0; k < 1; k++)
            {
                /* FIX: test for a zero denominator */
                if (data != 0)
                {
                    IO.WriteLine("100/" + data + " = " + (100 / data) + "\n");
                }
                else
                {
                    IO.WriteLine("This would result in a divide by zero");
                }
            }
        }
示例#54
0
        private void InitSocket()
        {
            try
            {
                tbxLocalIpAddress.Text =
                    Regex.Replace(tbxLocalIpAddress.Text, @"[^0-9].[^0-9].[^0-9].[^0-9]", "");
                tbxPort.Text = Regex.Replace(tbxPort.Text, @"[^0-9]", "");
                if (tbxLocalIpAddress.Text == "" || tbxPort.Text == "")
                {
                    MessageBox.Show("Local IP Address 또는 Port 번호가 올바르지 않습니다.");
                    throw new Exception();
                }
                TcpListner = new TcpListener(IPAddress.Parse(tbxLocalIpAddress.Text.Trim()), Int32.Parse(tbxPort.Text));
                TcpClient  = default(TcpClient);
                TcpListner.Start();
                DisplayText(">> server Started");
                while (true)
                {
                    try
                    {
                        TcpClient = TcpListner.AcceptTcpClient();
                        NetworkStream stream = TcpClient.GetStream();
                        stream = TcpClient.GetStream();

                        byte[] sizeBuf = new byte[TcpClient.ReceiveBufferSize];
                        stream.Read(sizeBuf, 0, (int)TcpClient.ReceiveBufferSize);
                        int size = BitConverter.ToInt32(sizeBuf, 0);

                        MemoryStream memoryStream = new MemoryStream();

                        while (size > 0)
                        {
                            byte[] buffer;
                            if (size < TcpClient.ReceiveBufferSize)
                            {
                                buffer = new byte[size];
                            }
                            else
                            {
                                buffer = new byte[TcpClient.ReceiveBufferSize];
                            }

                            int rec = stream.Read(buffer, 0, buffer.Length);

                            size -= rec;
                            memoryStream.Write(buffer, 0, buffer.Length);
                        }
                        memoryStream.Close();
                        byte[] data = memoryStream.ToArray();
                        memoryStream.Dispose();

                        string channel = Encoding.UTF8.GetString(data);
                        this.Invoke(new DeligateGetClientIP(GetClientIP), channel);
                        ClientList.Add(TcpClient, channel);
                        SendMessageAll(ClientIP + "/ 님이 연결되었습니다.", channel, true);

                        HandleClient handle = new HandleClient();
                        handle.OnReceived     += new HandleClient.MessageDisplayHandler(OnReceived);
                        handle.OnDisconnected += new HandleClient.DisconnectedHandler(OnDisconnected);
                        handle.StartClient(TcpClient, ClientList);
                    }
                    catch
                    {
                        throw new SocketException();
                    }
                }
            }
            catch (SocketException ex)
            {
                this.Invoke(new DeligateDisconnect(Disconnect));
                ServerEvent.ErrorLog("InitSocket", ex.Message);
            }
            catch (Exception ex)
            {
                ServerEvent.ErrorLog("InitSocket", ex.Message);
            }
            finally
            {
                this.Invoke(new DeligateButtonChange(ButtonStatusChange));
            }
        }
        public Task Run()
        {
            Core.Instance.Log.InfoFormat("Starting EnhancedRestoreChunkProtocol: {0}", _fileChunk);
            return(Task.Factory.StartNew(() =>
            {
                Core.Instance.MCChannel.Send(new GetChunkMessage(_fileChunk));

                var src1 = Core.Instance.MDRChannel.Received
                           .Where(message => message.MessageType == MessageType.Chunk)
                           .Cast <ChunkMessage>()
                           .Where(message => message.ChunkNo == _fileChunk.ChunkNo &&
                                  message.FileId == _fileChunk.FileId)
                           .Cast <Message>();

                var src2 = Core.Instance.MDRChannel.Received
                           .Where(message => message.MessageType == MessageType.ACK)
                           .Cast <ACKMessage>()
                           .Where(message => message.ChunkNo == _fileChunk.ChunkNo &&
                                  message.FileId == _fileChunk.FileId)
                           .Cast <Message>();

                Message msg;
                try
                {
                    // wait for response
                    msg = src1.Merge(src2).Timeout(TimeSpan.FromMilliseconds(Timeout))
                          .Next().First();
                }
                catch (TimeoutException)
                {
                    Core.Instance.Log.ErrorFormat("EnhancedRestoreChunkProtocol: Could not fetch {0} from the network (timeout).", _fileChunk);
                    return;
                }

                if (msg.MessageType == MessageType.Chunk) // same behaviour as the regular protocol
                {
                    Message = msg as ChunkMessage;
                    return;
                }

                var ackMessage = msg as ACKMessage;
                if (ackMessage == null)
                {
                    Core.Instance.Log.ErrorFormat("EnhancedRestoreChunkProtocol: could not cast message {0} to ACK", msg);
                    return;
                }

                var listener = new TcpListener(IPAddress.Any, 0);
                listener.Start();

                Core.Instance.MCChannel.Send(new ConnInfoMessage(_fileChunk, ((IPEndPoint)listener.LocalEndpoint).Port,
                                                                 ackMessage.RemoteEndPoint.Address));

                var clientTask = listener.AcceptTcpClientAsync();
                if (!clientTask.Wait(Timeout))
                {
                    Core.Instance.Log.Error("EnhancedRestoreChunkProtocol: listener.AcceptTcpClientAsync timed out");
                    return;
                }

                Core.Instance.Log.Info("EnhancedRestoreChunkProtocol: TcpClient accepted");
                try
                {
                    var stream = clientTask.Result.GetStream();
                    var bytes = new byte[Core.Instance.Config.ChunkSize];
                    var bytesRead = stream.Read(bytes, 0, bytes.Length);
                    Message = new ChunkMessage(_fileChunk, bytes.Take(bytesRead).ToArray());
                    clientTask.Result.Close();
                }
                catch (Exception)
                {
                    Core.Instance.Log.Error("EnhancedRestoreChunkProtocol: error receiving chunk");
                }

                Core.Instance.Log.Info("EnhancedRestoreChunkProtocol: chunk was received with success");
            }));
        }
示例#56
0
        // Main thread for receiving telegrams
        private void RcvThreading()
        {
            try
            {
                if (SimulateMFCS)
                {
                    RcvListener = new TcpListener(RcvIPEndPoint);
                    Log.AddLog(Log.Severity.EVENT, Name, "Communication.RcvThreading", RcvIPEndPoint.ToString());
                    RcvListener.Start();
                }


                LastReceiveTime = DateTime.Now;

                while (Thread.CurrentThread.ThreadState == ThreadState.Background)
                {
                    try
                    {
                        RcvTelegrams.RemoveAll(p => p.CommRcvStatus >= Telegram.CommRcvStatusEnum.NotifyDone);
                        if (DateTime.Now - LastReceiveTime > RcvTimeOut)
                        {
                            InitRcvSocket();
                            LastReceiveTime = DateTime.Now;
                            Log.AddLog(Log.Severity.EVENT, Name, "Communication.RcvThreading", "Timeout receiving");
                        }
                        else if (DateTime.Now - LastNotifyTime > RefreshTime)
                        {
                            LastNotifyTime = DateTime.Now;
                            Log.AddLog(Log.Severity.EVENT, Name, "Communication.RcvThreading", "Refresh() is called");
                            OnRefresh.ForEach(prop => prop?.Invoke());
                        }
                        else if (!RcvSocket.Connected)
                        {
                            InitRcvSocket();
                            ConnectRcvPartner();
                        }
                        else
                        {
                            if (RcvSocket.Available == 0)
                            {
                                Thread.Sleep(1);
                            }
                            else
                            {
                                Telegram tel     = new TelegramOnlyHeader();
                                int      numRead = 0;
                                do
                                {
                                    numRead += RcvSocket.Receive(tel.ByteBuffer, numRead, tel.ByteBuffer.Length - numRead, SocketFlags.None);
                                } while (numRead < tel.ByteBuffer.Length);
                                // Log.AddLog(Log.Severity.EVENT, Name, "Communication.RcvThreading", String.Format("Received {0} bytes", numRead));
                                tel.ReadBuffer();
                                tel.Validate(false);
                                Telegram tel1 = Activator.CreateInstance(AllTelegrams[tel.TelType].GetType()) as Telegram;
                                tel.ByteBuffer.CopyTo(tel1.ByteBuffer, 0);
                                if (tel1.DesignLength() - tel.DesignLength() > 0 && tel.TelCode == 0)
                                {
                                    numRead = 0;
                                    do
                                    {
                                        numRead += RcvSocket.Receive(tel1.ByteBuffer, tel.DesignLength() + numRead, tel1.DesignLength() - tel.DesignLength() - numRead, SocketFlags.None);
                                    } while (numRead < tel1.DesignLength() - tel.DesignLength());
                                    // Log.AddLog(Log.Severity.EVENT, Name, "Communication.RcvThreading", String.Format("Received {0} bytes", numRead));
                                }
                                tel1.ReadBuffer();
                                tel1.Validate();
                                NotifyRcv(tel1);
                                TelegramACK telACK = new TelegramACK();
                                telACK.Sequence = tel.Sequence;
                                telACK.TelCode  = (System.UInt16) 0xFFFF;
                                telACK.TelType  = tel.TelType;
                                telACK.Sender   = tel.Receiver;
                                telACK.Receiver = tel.Sender;
                                telACK.Build();
                                RcvSocket.Send(telACK.ByteBuffer);
                                Log.AddLog(Log.Severity.EVENT, Name, "Communication.RcvThreading", String.Format("ACK sended {0}", telACK.ToString()));
                                tel1.CommRcvStatus = Telegram.CommRcvStatusEnum.Ack;
                                RcvTelegrams.Add(tel1);
                                LastReceiveTime = DateTime.Now;
                                LastNotifyTime  = DateTime.Now;
                                Log.AddLog(Log.Severity.EVENT, Name, "Communication.RcvThreading", String.Format("Received finished : {0}", tel1.ToString()));
                            }
                        }
                    }
                    catch (SocketException ex)
                    {
                        Log.AddLog(Log.Severity.EXCEPTION, Name, "Communication.RcvThreading::Socket", ex.Message);
                        Thread.Sleep(1000);
                    }
                    catch (TelegramException ex)
                    {
                        Log.AddLog(Log.Severity.EXCEPTION, Name, "Communication.RcvThreading::Telegram", ex.Message);
                        Thread.Sleep(1000);
                    }
                    catch (KeyNotFoundException ex)
                    {
                        Log.AddLog(Log.Severity.EXCEPTION, Name, "Communication.RcvThreading::KeyNotFound", ex.Message);
                        Thread.Sleep(1000);
                    }
                    catch (CommunicationException ex)
                    {
                        Log.AddLog(Log.Severity.EXCEPTION, Name, "Communication.RcvThreading::Communication", ex.Message);
                        Thread.Sleep(1000);
                    }
                    catch (ThreadAbortException ex)
                    {
                        Log.AddLog(Log.Severity.EXCEPTION, Name, "Communication.RcvThreading::Communication", ex.Message);
                        return;
                    }
                    catch (Exception ex)
                    {
                        Log.AddLog(Log.Severity.EXCEPTION, Name, "Communication.SendThread::unknown", ex.Message);
                        Thread.Sleep(1000);
                    }
                }
            }
            finally
            {
                RcvSocket.Close();
                RcvSocket.Dispose();
                SendSocket.Close();
                SendSocket.Dispose();
            }
        }
        private static double BadSource()
        {
            double data;

            data = double.MinValue; /* Initialize data */
            /* Read data using a listening tcp connection */
            {
                TcpListener  listener = null;
                TcpClient    tcpConn  = null;
                StreamReader sr       = null;
                /* Read data using a listening tcp connection */
                try
                {
                    listener = new TcpListener(IPAddress.Parse("10.10.1.10"), 39543);
                    tcpConn  = listener.AcceptTcpClient();
                    /* read input from socket */
                    sr = new StreamReader(tcpConn.GetStream());
                    /* FLAW: Read data using a listening tcp connection */
                    string stringNumber = sr.ReadLine();
                    if (stringNumber != null) // avoid NPD incidental warnings
                    {
                        try
                        {
                            data = double.Parse(stringNumber.Trim());
                        }
                        catch (FormatException exceptNumberFormat)
                        {
                            IO.Logger.Log(NLog.LogLevel.Warn, exceptNumberFormat, "Number format exception parsing data from string");
                        }
                    }
                }
                catch (IOException exceptIO)
                {
                    IO.Logger.Log(NLog.LogLevel.Warn, exceptIO, "Error with stream reading");
                }
                finally
                {
                    /* Close stream reading objects */
                    try
                    {
                        if (sr != null)
                        {
                            sr.Close();
                        }
                    }
                    catch (IOException exceptIO)
                    {
                        IO.Logger.Log(NLog.LogLevel.Warn, exceptIO, "Error closing StreamReader");
                    }

                    /* Close socket objects */
                    try
                    {
                        if (tcpConn != null)
                        {
                            tcpConn.Close();
                        }
                    }
                    catch (IOException exceptIO)
                    {
                        IO.Logger.Log(NLog.LogLevel.Warn, exceptIO, "Error closing TcpClient");
                    }

                    try
                    {
                        if (listener != null)
                        {
                            listener.Stop();
                        }
                    }
                    catch (IOException exceptIO)
                    {
                        IO.Logger.Log(NLog.LogLevel.Warn, exceptIO, "Error closing TcpListener");
                    }
                }
            }
            return(data);
        }
示例#58
0
 public override void Bad()
 {
     int count;
     while (true)
     {
         count = int.MinValue; /* Initialize count */
         /* Read data using a listening tcp connection */
         {
             TcpListener listener = null;
             /* Read data using a listening tcp connection */
             try
             {
                 listener = new TcpListener(IPAddress.Parse("10.10.1.10"), 39543);
                 listener.Start();
                 using (TcpClient tcpConn = listener.AcceptTcpClient())
                 {
                     /* read input from socket */
                     using (StreamReader sr = new StreamReader(tcpConn.GetStream()))
                     {
                         /* POTENTIAL FLAW: Read count using a listening tcp connection */
                         string stringNumber = sr.ReadLine();
                         if (stringNumber != null) // avoid NPD incidental warnings
                         {
                             try
                             {
                                 count = int.Parse(stringNumber.Trim());
                             }
                             catch(FormatException exceptNumberFormat)
                             {
                                 IO.Logger.Log(NLog.LogLevel.Warn, exceptNumberFormat, "Number format exception parsing count from string");
                             }
                         }
                     }
                 }
             }
             catch (IOException exceptIO)
             {
                 IO.Logger.Log(NLog.LogLevel.Warn, exceptIO, "Error with stream reading");
             }
             finally
             {
                 try
                 {
                     if (listener != null)
                     {
                         listener.Stop();
                     }
                 }
                 catch(SocketException se)
                 {
                     IO.Logger.Log(NLog.LogLevel.Warn, se, "Error closing TcpListener");
                 }
             }
         }
         break;
     }
     while (true)
     {
         int i = 0;
         /* POTENTIAL FLAW: For loop using count as the loop variant and no validation */
         for (i = 0; i < count; i++)
         {
             IO.WriteLine("Hello");
         }
         break;
     }
 }
 public void Start()
 {
     m_tcpListener = new TcpListener(IPAddress.Loopback, m_port);
     m_tcpListener.Start();
     UnityEngine.Debug.Log("Listening for python interpreter commands on port " + m_port);
     m_tcpListener.BeginAcceptTcpClient(HandleClientComm, null);
 }
        /// <summary>
        /// Constructor
        /// </summary>
        public ListenerSocket()
        {
            // Init
            loadBalancerSocket = new TcpClient();

            // Connect to the loadbalancer
            Console.Write("Enter the loadbalancer ip: "); // Prompt
            loadBalancerSocket.Connect(IPAddress.Parse(Console.ReadLine()), int.Parse(Server.Properties.Resources.LoadBalancerPort));
            Logger.ShowMessage(
                String.Format("Connected to loadbalancer on: {0}:{1} and {2}:{3}",
                    ((IPEndPoint)loadBalancerSocket.Client.LocalEndPoint).Address,
                    ((IPEndPoint)loadBalancerSocket.Client.LocalEndPoint).Port,
                    ((IPEndPoint)loadBalancerSocket.Client.RemoteEndPoint).Address,
                    ((IPEndPoint)loadBalancerSocket.Client.RemoteEndPoint).Port
                )
            );

            Clients = new List<TcpClient>();
            messageHandler = new MessageHandler();

            // Make the socket listener and thread
            Random randomPort = new Random();
            listenerSocket = new TcpListener(IPAddress.Any, randomPort.Next(8900, 9000));
            listenThread = new Thread(new ThreadStart(ListenForClients));
            listenThread.Start();

            sendServerPort(loadBalancerSocket, ((IPEndPoint)listenerSocket.LocalEndpoint).Port);
            Logger.ShowMessage("Listener initialized.");
            Logger.ShowMessage("Listening on: " + ((IPEndPoint)listenerSocket.LocalEndpoint).Address + ":" + ((IPEndPoint)listenerSocket.LocalEndpoint).Port);

            // Define the handlers.
            PacketManager.DefineOpcodeHandlers();
        }