简体   繁体   中英

How can i make my client-server app a multiclient-server app? C#

I have a little problem with setting my client-server app for multiple clients usage. I can connect to server and use one client. I modified a little the code to connect via second client, but i don't really know how can i read and send datas to server from second client that are visible also in first client and server. Any ideas/help? Thanks in advance!

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

using System.Net;
using System.Net.Sockets;
using System.IO;
using System.Threading;

namespace Server_WF
{
    public partial class Form1 : Form
    {
        private TcpClient client;
        static List<TcpListener> listeners = new List<TcpListener>(); 
        public StreamReader SR;
        public StreamWriter SW;
        public string otrzymano;
        public String msg;

        public Form1()
        {
            InitializeComponent();

            IPAddress[] localIP = Dns.GetHostAddresses(Dns.GetHostName());  // Pobieranie własnego IP
            foreach(IPAddress adres in localIP)
            {
                if (adres.AddressFamily == AddressFamily.InterNetwork)
                {
                    textBox3.Text = adres.ToString();
                }
            }
        }

        private void button2_Click(object sender, EventArgs e) // START SERVER
        {
            TcpListener listener = new TcpListener(IPAddress.Any, int.Parse(textBox4.Text));
            listeners.Add(listener);
            listener.Start();
            client = listener.AcceptTcpClient();
            SR = new StreamReader(client.GetStream());
            SW = new StreamWriter(client.GetStream());
            SW.AutoFlush = true;

            backgroundWorker1.RunWorkerAsync();                     // Rozpocznij odbieranie danych
            backgroundWorker2.WorkerSupportsCancellation = true;    // Zdolność do usunięcia wątku

        }

        private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e) // Odbieranie danych
        {
            while(client.Connected)
            {
                try
                {
                    otrzymano = SR.ReadLine();
                    this.textBox2.Invoke(new MethodInvoker(delegate() { textBox2.AppendText("Ktoś: " + otrzymano + "\n"); }));
                    otrzymano = "";
                }
                catch(Exception x)
                {
                    MessageBox.Show(x.Message.ToString());
                }
            }
        }

        private void backgroundWorker2_DoWork(object sender, DoWorkEventArgs e) // Przesyłanie danych
        {
            if(client.Connected)
            {
                SW.WriteLine(msg);
                this.textBox2.Invoke(new MethodInvoker(delegate() { textBox2.AppendText("Ja: " + msg + "\n"); }));
            }
            else 
            {
                MessageBox.Show("Wysyłanie nie powiodło się.");
            }
            backgroundWorker2.CancelAsync();
        }

        private void button3_Click(object sender, EventArgs e)  // Połącz z serwerem
        {
            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("Połączono z serwerem..." + "\n");
                    SW = new StreamWriter(client.GetStream());
                    SR = new StreamReader(client.GetStream());
                    SW.AutoFlush = true;

                    backgroundWorker1.RunWorkerAsync();                     // Rozpocznij odbieranie danych
                    backgroundWorker2.WorkerSupportsCancellation = true;    // Zdolność do usunięcia wątku
                }
            }
            catch(Exception x)
            {
                MessageBox.Show(x.Message.ToString());
            }
        }

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

Oh dear, there's a lot to do in your code. First of all: don't call CancelAsync from your background worker code. It is not necessary and probably causes problem. Also, a background worker should never ever display MessageBoxes !

Secondly, a background worker is not the right tool in this case!

Thirdly: You need to make your code completely asynchronous. So please look into the BeginAcceptTcpClient . Then, handle each connected client in its own thread (NOT background worker!).

It's probably best you google for examples on how to do this, as this would be far too much to write up here.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM