通过Async Server客户端聊天C#发送图像

时间:2016-05-24 04:17:58

标签: c# server client

我是C#开发的新手。我正在研究服务器客户端聊天应用程序,我希望在服务器和客户端之间启用图像交换功能。我已经尝试了很多在线教程,但没有一个适应我的代码。以下是我的代码:

namespace ServerClientChat
{   


   {

公共部分类Form1:表单     {         私有TcpClient客户端;         public StreamReader STR;         public StreamWriter STW;         公共字符串接收;

    public Image img_to_receive;
    public String text_to_send;
    public Image img_to_send;
    public String UserName = "Asad";



    public Form1()
    {

        InitializeComponent();

        IPAddress[] localIP = Dns.GetHostAddresses(Dns.GetHostName()); //getting own IP
        foreach (IPAddress address in localIP)
        {
            if (address.AddressFamily == AddressFamily.InterNetwork)
            {
                textBox3.Text = address.ToString();


            }
        }

     //   textBox1.KeyDown += new KeyEventHandler(textBox1_KeyDown);
    }



    private void button3_Click(object sender, EventArgs e) //Connect to server
    {
        if (string.IsNullOrWhiteSpace(this.textBox7.Text))
        {
            MessageBox.Show("Please enter a Username.");
        }

        else if (string.IsNullOrWhiteSpace(this.textBox5.Text))
        {
            MessageBox.Show("Please enter an IP address.");
        }

        else if (string.IsNullOrWhiteSpace(this.textBox6.Text))
        {
            MessageBox.Show("Please enter a Port number.");
        }

        else
        {
            textBox7.Enabled = false;
            textBox2.Enabled = false;
            textBox5.Enabled = false;
            textBox6.Enabled = false;
            client = new TcpClient();
            //set client side endpoint consisting of client's ip address and port
            IPEndPoint IP_End = new IPEndPoint(IPAddress.Parse(textBox5.Text), int.Parse(textBox6.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 background (async means non-blocked communication
                    backgroundWorker2.WorkerSupportsCancellation = true;  //ability to cancel this thread

                }

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

        }
    }

    private void button2_Click(object sender, EventArgs e) //Start server
    {
        if (string.IsNullOrWhiteSpace(this.textBox7.Text))
        { 
            MessageBox.Show("Please enter a Username.");
        }
       else if (string.IsNullOrWhiteSpace(this.textBox4.Text))
        {
            MessageBox.Show("Please enter a Port number.");
        }

        else
        {
            textBox7.Enabled = false;
            textBox3.Enabled = false;
            textBox4.Enabled = false;
            textBox2.Enabled = false;
            TcpListener listener = new TcpListener(IPAddress.Any, int.Parse(textBox4.Text)); //Listens for connections from TCP network clients.
            listener.Start();
            client = listener.AcceptTcpClient();
            STR = new StreamReader(client.GetStream()); //Implements a TextReader that reads characters from a byte stream in a particular encoding.
            STW = new StreamWriter(client.GetStream());
            STW.AutoFlush = true; //Setting AutoFlush to true means that data will be flushed from the buffer to the stream after each write operation, but the encoder state will not be flushed.

            backgroundWorker1.RunWorkerAsync();  //start receiving data in background (async means non-blocked communication
            backgroundWorker2.WorkerSupportsCancellation = true;  //ability to cancel this thread
        }
    }

    private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e) //to receive data
    {
        while(client.Connected)
        {
            try

            {

                receive = STR.ReadLine();

                this.textBox2.Invoke(new MethodInvoker(delegate () { textBox2.AppendText( receive + "\n\n"); }));
                receive = ""; 
            }
            catch(Exception x)       

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

    private void backgroundWorker2_DoWork(object sender, DoWorkEventArgs e) //to send data
    {
        if(client.Connected)                            
        {
            STW.WriteLine(text_to_send);




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


        }
        else
        {
            MessageBox.Show("Send Failed");
        }
        backgroundWorker2.CancelAsync();
    }

    private void button1_Click(object sender, EventArgs e) //Send button
    {

           if(textBox1.Text!="")
        {
            text_to_send = textBox7.Text+":"+textBox1.Text;
            backgroundWorker2.RunWorkerAsync();
        }

        textBox1.Text = "";
    }

    private void Form1_Load(object sender, EventArgs e)
    {
        DialogResult f = MessageBox.Show("Welcome to My Chat App! Do you want to start your own Server? ", "Welcome!", MessageBoxButtons.YesNoCancel);
        if (f == DialogResult.Yes)
        {
            button3.Enabled = false;
            textBox5.Enabled = false;
            textBox6.Enabled = false;

        }

        if (f == DialogResult.No)
        {
            button2.Enabled = false;
            textBox3.Enabled = false;
            textBox4.Enabled = false;
        }

        if(f==DialogResult.Cancel)
        {
            this.Close();
        }

    }

    private void label5_Click(object sender, EventArgs e)
    {

    }

    private void textBox1_TextChanged(object sender, EventArgs e)
    {

    }

    private void textBox1_KeyDown(object sender, KeyEventArgs e)
    {
        if (e.KeyCode == Keys.Enter)
        {
            button1_Click(this, new EventArgs());
        }
    }

    private void button4_Click(object sender, EventArgs e)
    {


    }

    private void browsebtn_Click(object sender, EventArgs e)
    {

    }

    private void sendimg_Click(object sender, EventArgs e)
    {
        try
        {


        }

        catch(Exception c)
        {
            MessageBox.Show(c.Message);
        }
    }
}

}

0 个答案:

没有答案