简体   繁体   English

在C#中向服务器/客户端聊天添加用户名

[英]Add a username to Server/Client Chat in C#

I'm working on a Chat Application on Windows Form using C# Socket Programming. 我正在使用C#套接字编程在Windows窗体上的聊天应用程序上工作。 Currently, my App send messages as "ME" and receives messages as "FRIEND". 目前,我的应用程序以“ ME”发送消息,以“ FRIEND”接收消息。 What I want is to add a textbox which asks Client for username and server receives messages as that username. 我想要添加一个文本框,该文本框要求客户端提供用户名,服务器以该用户名接收消息。 Following is my code: 以下是我的代码:

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

        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
        {
            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
        {
            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("Friend: " + receive + "\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("Me: " + text_to_send + "\n"); }));

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

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

           if(textBox1.Text!="")
           {
                text_to_send = 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;
            }

        }

        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());
            }
        }
    }
}

You can create something like your own protocol and send it to a server. 您可以创建类似自己的协议的内容并将其发送到服务器。

<username>YourName</username>
<msg>Hello World</msg> 

But in real-life applications you should use database with user authorization process. 但是在现实生活中的应用程序中,您应该将数据库与用户授权过程一起使用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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