C#服务器 - 客户端应用程序(一个服务器 - 多客户端)

时间:2015-04-27 12:38:55

标签: c# multithreading client server

我想开发一个客户端 - 服务器应用程序。我启动了这个项目,但遇到了一些问题。当我想用一个客户端连接到服务器时,一切都已完成。计划正在运作。但是,当我想连接两台或三台PC等服务器时,它们的客户端正在工作,但其他客户端无法工作。我该如何解决这个问题?

这是我的代码;

    using System;
    using System.Collections.Generic;
    using System.ComponentModel;
    using System.Data;
    using System.Drawing;
    using System.Linq;
    using System.Text;
    using System.Threading;
    using System.Threading.Tasks;
    using System.Windows.Forms;
    using System.Net;
    using System.Net.Sockets;
    using System.IO;
    using System.Timers;
    using ClientServer;
    namespace ClientServer
    {
        public partial class Form1 : Form
        {
            private TcpClient Client;
            private StreamReader STR;
            public StreamWriter STW;
            public string receive;
            public string text_to_send;
            //int zaman;
            public Form1()
            {
                    InitializeComponent();
-                   Client = new TcpClient();
                    Control.CheckForIllegalCrossThreadCalls = false; //cross threading problem
                    IPAddress[] LocalIP = Dns.GetHostAddresses(Dns.GetHostName()); // my IP Adress
            foreach (IPAddress adress in LocalIP)
            {
                if(adress.AddressFamily== AddressFamily.InterNetwork)
                {
                    textBox3.Text = adress.ToString();

                }
            }
        }

        private void button2_Click(object sender, EventArgs e) //Start server
        {
            TcpListener listener = new TcpListener(IPAddress.Any, int.Parse(textBox4.Text));
            listener.Start();
            Client = listener.AcceptTcpClient();
            STR = new StreamReader(Client.GetStream());
            STW = new StreamWriter(Client.GetStream());
            STW.AutoFlush = true;

            backgroundWorker1.RunWorkerAsync();  //receive data background
            backgroundWorker2.WorkerSupportsCancellation = true; //ability cancel this thread


        }

        private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e) //receive data
        {
            while(Client.Connected)
            {
                try
                {
                    receive = STR.ReadLine();
                    if(receive=="soru1")
                    {
                        label7.Text = "Merhaba bu bir denemedir :)";
                        //zaman = 45;
                        timer1.Enabled = true;


                    }
                    this.textBox2.Invoke(new MethodInvoker(delegate() { textBox2.AppendText("Sen:" + receive + "\n"); }));

                    receive = "";
                }
                catch(Exception x)
                {
                    MessageBox.Show(x.Message.ToString());
                }
            }
        }



        private void backgroundWorker2_DoWork(object sender, DoWorkEventArgs e)  //veri gönder
        {
            if(Client.Connected)
            {
                STW.WriteLine(text_to_send);
                this.textBox2.Invoke(new MethodInvoker(delegate() { textBox2.AppendText("Ben:" + text_to_send + "\n"); }));

            }
            else
            {
                MessageBox.Show("Gönderim başarısız!");
            }
            backgroundWorker2.CancelAsync();

        }

        private void button3_Click(object sender, EventArgs e) //Connect Server
        {
            Client = new TcpClient();
            IPEndPoint IP_End = new IPEndPoint(IPAddress.Parse(textBox5.Text), int.Parse(textBox6.Text));

            try
            {
                Client.Connect(IP_End);
                if(Client.Connected)
                {
                    textBox2.AppendText("Server'a bağlantı sağlandı" + "\n");
                    STW = new StreamWriter(Client.GetStream());
                    STR = new StreamReader(Client.GetStream());
                    STW.AutoFlush = true;


                    backgroundWorker1.RunWorkerAsync();  //receive data in background
                    backgroundWorker2.WorkerSupportsCancellation = true; //

                }
            }
            catch(Exception x)
            {
                MessageBox.Show(x.Message.ToString());
            }
        }

        private void button1_Click(object sender, EventArgs e) //Send Button
        {
            if(textBox1.Text != "")
            {
                text_to_send = textBox1.Text;
                backgroundWorker2.RunWorkerAsync();
            }

            textBox1.Text = "";

        }

        //private void timer1_Tick(object sender, System.EventArgs e) //
        //{
        //    zaman--; //timer her saniyede sayıyı 1 azaltacak
        //    label9.Text = zaman.ToString();
        //    if (zaman == 0)
        //    {
        //        timer1.Enabled = false;
        //    }
        //}


    }
}

1 个答案:

答案 0 :(得分:2)

这里有一个很好的链接:

http://www.mikeadev.net/2012/07/multi-threaded-tcp-server-in-csharp/

https://www.codeproject.com/Articles/511814/Multi-client-per-one-server-socket-programming-in

tcpListener.Start();    
Console.WriteLine("************This is Server program************");    
Console.WriteLine("Hoe many clients are going to connect to this server?:");    
int numberOfClientsYouNeedToConnect =int.Parse( Console.ReadLine());

for (int i = 0; i < numberOfClientsYouNeedToConnect; i++)
{    
    Thread newThread = new Thread(new ThreadStart(Listeners));    
    newThread.Start();    
}