多客户服务器客户端c#

时间:2017-04-06 15:14:54

标签: c# server client client-server

所以最近我问了一个关于我在我的服务器 - 客户端程序中遇到的问题的问题,我可以解决问题,即使我在问题上得到的答案根本没有帮助(感谢无论如何:]),但现在我有另一个问题,我需要程序使它成为一个多客户端服务器类型的东西,我真的不知道该怎么做。我对ParameterizedThreadStart有疑问,我是如何把它用于工作等,我已经搜索过它,我知道它是一个线程方法,但仍然不知道我是如何使用它,任何想法?提前谢谢。

客户代码:

    public Form1()
    {

        InitializeComponent();

    }

    private void Form1_Load(object sender, EventArgs e) //connect to server
    {
        client = new TcpClient();
        IPEndPoint IP_End = new IPEndPoint(IPAddress.Parse("192.168.254.34"), 123); // sincronizacao do IP com a porta
        try
        {

            Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

            client.Connect(IP_End);

            if (client.Connected)
            {

                STW = new StreamWriter(client.GetStream());
                STR = new StreamReader(client.GetStream());
                STW.AutoFlush = true;

                backgroundWorker1.RunWorkerAsync(); // Começar a receber dados em background
                backgroundWorker1.WorkerSupportsCancellation = true; // possibilidade de cancelar o fio

            }
            else
            {

                reconnect();

            }

        }
        catch (SocketException exception)
        {

            MessageBox.Show(exception.Message.ToString());
            reconnect();
        }
    }

    public void reconnect()
    {
        try
        {

            IPEndPoint IP_End = new IPEndPoint(IPAddress.Parse("192.168.254.34"), 123); // sincronizacao do IP com a porta
            client.Connect(IP_End);

            STW = new StreamWriter(client.GetStream());
            STR = new StreamReader(client.GetStream());
            STW.AutoFlush = true;

            backgroundWorker1.RunWorkerAsync(); 
            backgroundWorker1.WorkerSupportsCancellation = true; 
        }
        catch (SocketException exception)
        {

            MessageBox.Show(exception.Message.ToString());
            reconnect();
        }
    }

    private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e) 
    {
        while(client.Connected) 
        {
            try
            {
                receive = STR.ReadLine();
                this.textBox2.Invoke(new MethodInvoker(delegate () { textBox2.Text=(receive + "\n\r"); }));

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

服务器代码:

public partial class Form1 : Form
{
    private TcpClient client;
    public StreamReader STR;
    public StreamWriter STW;
    public string receive;
    public String text_to_send;

    public Form1()
    {

        InitializeComponent();

    }

    private void backgroundWorker2_DoWork(object sender, DoWorkEventArgs e) 
    {
        if(client.Connected) //enquanto o cliente tiver conectado pode escrever para o servidor
        {
            STW.WriteLine(text_to_send);
            this.textBox2.Invoke(new MethodInvoker(delegate () { textBox2.Text= (text_to_send + "\n\r"); }));
        }
        else
        {
            MessageBox.Show("Envio Falhado!"); 
        }

    }

    private void button1_Click(object sender, EventArgs e) 
    {
        if (text_to_send != "" && textBox1.Text != "")
        {
            text_to_send = textBox1.Text;
            backgroundWorker2.RunWorkerAsync();
        }
        else {
            MessageBox.Show("Escreva uma mensagem para ser enviada");
        }
        textBox1.Text = "";
    }

    private void Form1_Load(object sender, EventArgs e) 
    {
        TcpListener Listener = new TcpListener(IPAddress.Any, 123); 

        Listener.Start();
        client = Listener.AcceptTcpClient();



        if (text_to_send != "")
        {
            text_to_send = "Conexão efetuada com sucesso...";
            backgroundWorker2.RunWorkerAsync();
        }

        STR = new StreamReader(client.GetStream());
        STW = new StreamWriter(client.GetStream());
        STW.AutoFlush = true; 

    }

}

服务器代码(正在处理):

    public Form1()
    {

        InitializeComponent();

    }

    private void backgroundWorker2_DoWork(object sender, DoWorkEventArgs e) 
    {
        if(client.Connected) 
        {
            STW.WriteLine(text_to_send);
            this.textBox2.Invoke(new MethodInvoker(delegate () { textBox2.Text= (text_to_send + "\n\r"); }));
        }
        else
        {
            MessageBox.Show("Envio Falhado!"); 
        }

    }

    private void button1_Click(object sender, EventArgs e) 
    {
        if (text_to_send != "" && textBox1.Text != "")
        {
            text_to_send = textBox1.Text;
            backgroundWorker2.RunWorkerAsync();
        }
        else {
            MessageBox.Show("Escreva uma mensagem para ser enviada");
        }
        textBox1.Text = "";
    }

    private void Form1_Load(object sender, EventArgs e) // criar server
    {

        this.threadTcp = new Thread(new ThreadStart(ListenToClients));

        Listener.Start();
        client = Listener.AcceptTcpClient();



        if (text_to_send != "")
        {
            text_to_send = "Conexão efetuada com sucesso...";
            backgroundWorker2.RunWorkerAsync();
        }

        STR = new StreamReader(client.GetStream());
        STW = new StreamWriter(client.GetStream());
        STW.AutoFlush = true; 
    }

    private void ListenToClients()
    {
        Listener.Start();
        while (true)
        {
            try
            {
                this.Listener.AcceptTcpClient();
                client = Listener.AcceptTcpClient();

                Thread threadClient = new Thread(new ParameterizedThreadStart(HandleClients));
                threadClient.Start(client);

            }
            catch (Exception)
            {
                MessageBox.Show("error");
            }
        }
    }
    private void HandleClients()
    {
        //TcpListener Listener = new TcpListener(IPAddress.Any, int.Parse(textBox4.Text)); 
        Listener.Start();
        client = Listener.AcceptTcpClient();



        if (text_to_send != "")
        {
            text_to_send = "Conexão efetuada com sucesso...";
            backgroundWorker2.RunWorkerAsync();
        }

        STR = new StreamReader(client.GetStream());
        STW = new StreamWriter(client.GetStream());
        STW.AutoFlush = true; 

    }

}

}

0 个答案:

没有答案