Ejemplo n.º 1
0
        private void button2_Click(object sender, EventArgs e)
        {
            f = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            f.Bind(new IPEndPoint(IPAddress.Any, int.Parse(textBox2.Text)));
            f.Listen(50000);

            label1.Text = string.Format("Listening for connections at {0}:{1}...", LocalIPAddress(), textBox2.Text);
            button2.Enabled = false;
            button3.Enabled = true;
            textBox2.ReadOnly = true;

            th = new Thread(new ThreadStart(delegate()
            {
                while (true)
                    try
                    {
                        new Thread(new ParameterizedThreadStart(delegate(object _socket)
                        {
                            Client cli = new Client((Socket)_socket, true, this, true);
                            //Ask to allow connection.
                            if (MessageBox.Show("Client is connecting from " + cli.RemoteIp + ". Allow this connection?", "Incoming Connection", MessageBoxButtons.YesNo, MessageBoxIcon.Information) == System.Windows.Forms.DialogResult.Yes)
                            {
                                //Client must be confirmed to send files, etc.
                                cli.Accepted = true;

                                Console.WriteLine("Client connected from " + cli.RemoteIp);

                                Utilities.clientx.Add(cli);
                                if(listBox1.InvokeRequired)
                                {
                                    listBox1.Invoke((MethodInvoker)(() => { listBox1.Items.Add(cli.RemoteIp); }));
                                }
                            }
                            else
                            {
                                cli.Disconnect();
                            }
                        })).Start(f.Accept());
                    }
                    catch { }
            }));
            th.Start();
            textBox1.Focus();
        }