使用表单和TCP协议(不是UDP)在C#中进行多客户端聊天

时间:2016-10-11 04:33:08

标签: c# forms winforms tcp tcpclient

我已经尝试了2个如何制作多个客户端,这是多线程和异步服务器。两者都不适合我。多线程可以使客户端向所有客户端发送广播,但是其中一些没有接收到广播的数据。虽然异步服务器无法使客户端连接太长时间。我不知道这是我的代码是错还是什么。请根据我最新的工作代码帮助我。

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Threading;
using System.Net;
using System.Net.Sockets;
using System.IO;

namespace Server
{
    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();

            IPAddress[] localIP = Dns.GetHostAddresses(Dns.GetHostName());      //Using the PC's IP
            foreach (IPAddress address in localIP) {
                if (address.AddressFamily == AddressFamily.InterNetwork) {
                    textBox5.Text = address.ToString();
                }
            }
        }

        private void Form1_Load(object sender, EventArgs e)
        {

        }

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

            backgroundWorker1.RunWorkerAsync(); //Start receiving data in the background
            backgroundWorker2.WorkerSupportsCancellation = true; //Cancel the active thread
        }

        private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e) //Receiving data
        {
            while(client.Connected)
            {
                try
                {
                    receive = STR.ReadLine();
                    this.textBox2.Invoke(new MethodInvoker(delegate() { textBox2.AppendText("You : " + receive + "\n   Received : " + receive.Length.ToString() + " byte. \n"); }));
                    receive = "";
                }
                catch(Exception x)
                {
                    MessageBox.Show(x.Message.ToString());

                }
            }
        }

        private void backgroundWorker2_DoWork(object sender, DoWorkEventArgs e) //Sending data
        {
            if (client.Connected)
            {
                STW.WriteLine(text_to_send);
                this.textBox2.Invoke(new MethodInvoker(delegate() { textBox2.AppendText("Me : " + text_to_send + "\n  Sent : " + text_to_send.Length.ToString() + " byte \n"); }));//Text that will appeared on the screen after we enter the text that we type
            }
            else
            {
                MessageBox.Show("Send Failed!");
            }
            backgroundWorker2.CancelAsync();
        }

        private void button3_Click(object sender, EventArgs e) //Connected as client
        {
            client = new TcpClient();
            IPEndPoint IP_End = new IPEndPoint(IPAddress.Parse(textBox3.Text), int.Parse(textBox4.Text));

            try
            {
                client.Connect(IP_End);
                if (client.Connected) {
                    textBox2.AppendText("Connected to server" + "\n");
                    STW = new StreamWriter(client.GetStream());
                    STR = new StreamReader(client.GetStream());
                    STW.AutoFlush = true;

                    backgroundWorker1.RunWorkerAsync(); //Start receiving data in the background
                    backgroundWorker2.WorkerSupportsCancellation = true; //Cancel the active thread
                }
            }
            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 label1_Click(object sender, EventArgs e)
        {

        }
    }
}

N.B:刚刚将评论翻译成英文

0 个答案:

没有答案