C#多线程编程---一个简单的聊天程序(Client)

接着上一篇,下面给出客户端的代码。             (1)Form1.cs[设计]界面 (2)Form1.cs[代码]
using System;

using System.Drawing;

using System.Collections;

using System.ComponentModel;

using System.Windows.Forms;

using System.Data;

using System.IO;

using System.Net;

using System.Net.Sockets;

using System.Threading;



namespace ChatClient

{

    public partial class Form1 : Form

    {

        NetworkStream ns;

        StreamReader sr;

        TcpClient clientsocket;

        delegate void AddContextCallBack(string AddContext);

        bool connected;

        Thread receive;

        Int16 serverport = 8000;

        string clientname;



        public Form1()

        {

            InitializeComponent();

        }



        private void EstablishConnection()

        {

            this.statusStrip1.Text = "正在连接到服务器...";

           

            try

            {

                clientsocket = new TcpClient("127.0.0.1", serverport);

                ns = clientsocket.GetStream();

                sr = new StreamReader(ns);

                if (clientsocket.Connected == true)

                {

                    connected = true;

                }

            }

            catch (ArgumentNullException ae)

            {

                Console.WriteLine("ArgumentNullException : {0}", ae.ToString());

            }

            catch (SocketException se)

            {

                Console.WriteLine("SocketException : {0}", se.ToString());

            }

            catch (Exception ex)

            {

                MessageBox.Show(ex.ToString());

                MessageBox.Show("不能连接到服务器!", "错误",

                 MessageBoxButtons.OK, MessageBoxIcon.Exclamation);

                statusStrip1.Text = "已断开连接";

            }

        }



        private void RegisterWithServer()

        {

            lbChatters.Items.Clear();



            clientname = clientName.Text;

            try

            {

                string command = "CONN|" + clientname; //+"/r/n";

                Byte[] outbytes = System.Text.Encoding.ASCII.GetBytes(command.ToCharArray());

                ns.Write(outbytes, 0, outbytes.Length);



                string serverresponse = sr.ReadLine();



                serverresponse.Trim();

                string[] tokens = serverresponse.Split('|');

                if (tokens[0] == "LIST")

                {

                    statusStrip1.Text = "已连接";

                    btnDisconnect.Enabled = true;

                }

                if (tokens[1] != "")

                {

                    for (int n = 1; n < tokens.Length; n++)

                        lbChatters.Items.Add(tokens[n].Trim(new char[] { '/r', '/n' }));

                }

                this.Text = clientname + ":已连接到服务器";



            }

            catch (Exception ex)

            {

                MessageBox.Show("注册时发生错误!" + ex.Message, "错误",

                 MessageBoxButtons.OK, MessageBoxIcon.Exclamation);

                connected = false;

            }

        }



        private void ReceiveChat()

        {

            bool keepalive = true;

            SetText("Start..." + "/r/n");

            while (keepalive)

            {

                try

                {

                    Byte[] buffer = new Byte[1024]; // 2048???

                    ns.Read(buffer, 0, buffer.Length);

                    string chatter = System.Text.Encoding.ASCII.GetString(buffer);

                    string[] tokens = chatter.Split(new Char[] { '|' });



                    if (tokens[0] == "CHAT")

                    {

                        SetText(tokens[1]);

                    }

                    if (tokens[0] == "PRIV")

                    {

                        SetText("Private from ");

                        SetText(tokens[1].Trim());

                        SetText(tokens[2] + "/r/n");

                    }

                    if (tokens[0] == "JOIN")

                    {

                        SetText(tokens[1].Trim());

                        SetText(" has joined the Chat/r/n");

                        string newguy = tokens[1].Trim(new char[] { '/r', '/n' });

                        lbChatters.Items.Add(newguy);

                    }

                    if (tokens[0] == "GONE")

                    {

                        SetText(tokens[1].Trim());

                        SetText(" has left the Chat/r/n");

                        lbChatters.Items.Remove(tokens[1].Trim(new char[] { '/r', '/n' }));

                    }

                    if (tokens[0] == "QUIT")

                    {

                        ns.Close();

                        clientsocket.Close();

                        keepalive = false;

                        statusStrip1.Text = "服务器端已停止";

                        connected = false;

                        btnSend.Enabled = false;

                        btnDisconnect.Enabled = false;

                    }

                }

                catch (Exception) { }

            }

        }



        private void QuitChat()

        {

            if (connected)

            {

                try

                {

                    string command = "GONE|" + clientname;

                    Byte[] outbytes = System.Text.Encoding.ASCII.GetBytes(command.ToCharArray());

                    ns.Write(outbytes, 0, outbytes.Length);

                    clientsocket.Close();

                }

                catch (Exception ex)

                {

                    MessageBox.Show(ex.Message);

                }

            }

            if (receive != null && receive.IsAlive)

                receive.Abort();

            this.Text = "客户端";



            connected = false;



        }



        private void btnSend_Click(object sender, EventArgs e)

        {

            if (connected)

            {

                try

                {

                    string command = "CHAT|" + clientname + ": " + ChatOut.Text + "/r/n";

                    Byte[] outbytes = System.Text.Encoding.ASCII.GetBytes(command.ToCharArray());

                    ns.Write(outbytes, 0, outbytes.Length);

                    //clientsocket.Close();

                }

                catch (Exception ex)

                {

                    MessageBox.Show(ex.Message);

                }

            }

        }



        private void btnConnect_Click(object sender, EventArgs e)

        {

           

            EstablishConnection();

            RegisterWithServer();

            if (connected)

            {

                receive = new Thread(new ThreadStart(ReceiveChat));

                receive.Start();

            }

        }



        private void btnDisconnect_Click(object sender, EventArgs e)

        {

            QuitChat();

        }



        private void SetText(string strTemp)

        {

            if (this.rtbChatIn.InvokeRequired)

            {

                AddContextCallBack d = new AddContextCallBack(SetText);

                this.Invoke(d, new object[] { strTemp });

            }

            else

            {

                this.rtbChatIn.AppendText(strTemp);

            }

        }

    }

}
(3)Form1.Designer.cs
namespace ChatClient

{

    partial class Form1

    {

        /// <summary>

        /// 必需的设计器变量。

        /// </summary>

        private System.ComponentModel.IContainer components = null;



        /// <summary>

        /// 清理所有正在使用的资源。

        /// </summary>

        /// <param name="disposing">如果应释放托管资源,为 true;否则为 false。</param>

        protected override void Dispose(bool disposing)

        {

            if (disposing)

            {

                if (receive != null)

                {

                    QuitChat();

                }

                if (components != null)

                {

                    components.Dispose();

                }

            }

            base.Dispose(disposing);

        }



        #region Windows 窗体设计器生成的代码



        /// <summary>

        /// 设计器支持所需的方法 - 不要

        /// 使用代码编辑器修改此方法的内容。

        /// </summary>

        private void InitializeComponent()

        {

            this.statusStrip1 = new System.Windows.Forms.StatusStrip();

            this.checkBox1 = new System.Windows.Forms.CheckBox();

            this.rtbChatIn = new System.Windows.Forms.RichTextBox();

            this.btnDisconnect = new System.Windows.Forms.Button();

            this.btnSend = new System.Windows.Forms.Button();

            this.ChatOut = new System.Windows.Forms.TextBox();

            this.clientName = new System.Windows.Forms.TextBox();

            this.lbChatters = new System.Windows.Forms.ListBox();

            this.btnConnect = new System.Windows.Forms.Button();

            this.SuspendLayout();

            //

            // statusStrip1

            //

            this.statusStrip1.Location = new System.Drawing.Point(0, 308);

            this.statusStrip1.Name = "statusStrip1";

            this.statusStrip1.Size = new System.Drawing.Size(460, 22);

            this.statusStrip1.TabIndex = 0;

            this.statusStrip1.Text = "statusStrip1";

            //

            // checkBox1

            //

            this.checkBox1.AutoSize = true;

            this.checkBox1.Location = new System.Drawing.Point(86, 286);

            this.checkBox1.Name = "checkBox1";

            this.checkBox1.Size = new System.Drawing.Size(78, 16);

            this.checkBox1.TabIndex = 1;

            this.checkBox1.Text = "checkBox1";

            this.checkBox1.UseVisualStyleBackColor = true;

            //

            // rtbChatIn

            //

            this.rtbChatIn.Location = new System.Drawing.Point(151, 3);

            this.rtbChatIn.Name = "rtbChatIn";

            this.rtbChatIn.Size = new System.Drawing.Size(291, 245);

            this.rtbChatIn.TabIndex = 2;

            this.rtbChatIn.Text = "";

            //

            // btnDisconnect

            //

            this.btnDisconnect.Enabled = false;

            this.btnDisconnect.Location = new System.Drawing.Point(11, 261);

            this.btnDisconnect.Name = "btnDisconnect";

            this.btnDisconnect.Size = new System.Drawing.Size(69, 19);

            this.btnDisconnect.TabIndex = 3;

            this.btnDisconnect.Text = "btnDisconnect";

            this.btnDisconnect.UseVisualStyleBackColor = true;

            this.btnDisconnect.Click += new System.EventHandler(this.btnDisconnect_Click);

            //

            // btnSend

            //

            this.btnSend.Location = new System.Drawing.Point(371, 258);

            this.btnSend.Name = "btnSend";

            this.btnSend.Size = new System.Drawing.Size(71, 22);

            this.btnSend.TabIndex = 4;

            this.btnSend.Text = "btnSend";

            this.btnSend.UseVisualStyleBackColor = true;

            this.btnSend.Click += new System.EventHandler(this.btnSend_Click);

            //

            // ChatOut

            //

            this.ChatOut.Location = new System.Drawing.Point(151, 258);

            this.ChatOut.Name = "ChatOut";

            this.ChatOut.Size = new System.Drawing.Size(214, 21);

            this.ChatOut.TabIndex = 5;

            //

            // clientName

            //

            this.clientName.Location = new System.Drawing.Point(12, 227);

            this.clientName.Name = "clientName";

            this.clientName.Size = new System.Drawing.Size(133, 21);

            this.clientName.TabIndex = 6;

            //

            // lbChatters

            //

            this.lbChatters.FormattingEnabled = true;

            this.lbChatters.ItemHeight = 12;

            this.lbChatters.Location = new System.Drawing.Point(12, 3);

            this.lbChatters.Name = "lbChatters";

            this.lbChatters.Size = new System.Drawing.Size(133, 208);

            this.lbChatters.TabIndex = 7;

            //

            // btnConnect

            //

            this.btnConnect.Location = new System.Drawing.Point(12, 286);

            this.btnConnect.Name = "btnConnect";

            this.btnConnect.Size = new System.Drawing.Size(68, 19);

            this.btnConnect.TabIndex = 8;

            this.btnConnect.Text = "btnConnect";

            this.btnConnect.UseVisualStyleBackColor = true;

            this.btnConnect.Click += new System.EventHandler(this.btnConnect_Click);

            //

            // Form1

            //

            this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 12F);

            this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;

            this.ClientSize = new System.Drawing.Size(460, 330);

            this.Controls.Add(this.btnConnect);

            this.Controls.Add(this.lbChatters);

            this.Controls.Add(this.clientName);

            this.Controls.Add(this.ChatOut);

            this.Controls.Add(this.btnSend);

            this.Controls.Add(this.btnDisconnect);

            this.Controls.Add(this.rtbChatIn);

            this.Controls.Add(this.checkBox1);

            this.Controls.Add(this.statusStrip1);

            this.Name = "Form1";

            this.Text = "聊天软件客户端";

            this.ResumeLayout(false);

            this.PerformLayout();



        }



        #endregion



        private System.Windows.Forms.StatusStrip statusStrip1;

        private System.Windows.Forms.CheckBox checkBox1;

        private System.Windows.Forms.RichTextBox rtbChatIn;

        private System.Windows.Forms.Button btnDisconnect;

        private System.Windows.Forms.Button btnSend;

        private System.Windows.Forms.TextBox ChatOut;

        private System.Windows.Forms.TextBox clientName;

        private System.Windows.Forms.ListBox lbChatters;

        private System.Windows.Forms.Button btnConnect;

    }

}
注:私聊还有问题,没有解决。        如果你还看到别的问题,请连同解决代码一起给我。我会及时更新的。        Email:jobsmeng@QQ.com        谢谢!!
  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值