Form1.cs
资源名称:Visual.rar [点击查看]
上传用户:yiyuerguo
上传日期:2014-09-27
资源大小:3781k
文件大小:13k
源码类别:
C#编程
开发平台:
Others
- using System;
- using System.Drawing;
- using System.Collections;
- using System.ComponentModel;
- using System.Windows.Forms;
- using System.Data;
- using System.Net.Sockets;
- using System.IO;
- using System.Threading;
- using System.Text;
- namespace ChatClient
- {
- /// <summary>
- /// Form1 的摘要说明。
- /// </summary>
- public class Form1 : System.Windows.Forms.Form
- {
- private System.Windows.Forms.StatusBar statusBar1;
- private System.Windows.Forms.Button btnDisconnect;
- private System.Windows.Forms.Button btnConnect;
- private System.Windows.Forms.Button btnLog;
- private System.Windows.Forms.CheckBox cbPrivate;
- private System.Windows.Forms.Button btnSend;
- private System.Windows.Forms.TextBox ChatOut;
- private System.Windows.Forms.RichTextBox rtbChatIn;
- private System.Windows.Forms.ListBox lbChatters;
- private int serverport;
- private NetworkStream ns;
- private StreamReader sr;
- private TcpClient clientsocket;
- private Thread receive = null;
- private string serveraddress;
- private string clientname;
- private bool connected = false;
- private bool logging = false;
- private bool privatemode = false;
- private StreamWriter logwriter;
- /// <summary>
- /// 必需的设计器变量。
- /// </summary>
- private System.ComponentModel.Container components = null;
- public Form1()
- {
- //
- // Windows 窗体设计器支持所必需的
- //
- InitializeComponent();
- //
- // TODO: 在 InitializeComponent 调用后添加任何构造函数代码
- //
- serverport = 5555;
- btnDisconnect.Enabled = false;
- btnSend.Enabled = false;
- }
- /// <summary>
- /// 清理所有正在使用的资源。
- /// </summary>
- protected override void Dispose( bool disposing )
- {
- if( disposing )
- {
- if (components != null)
- {
- components.Dispose();
- }
- }
- base.Dispose( disposing );
- }
- #region Windows Form Designer generated code
- /// <summary>
- /// 设计器支持所需的方法 - 不要使用代码编辑器修改
- /// 此方法的内容。
- /// </summary>
- private void InitializeComponent()
- {
- this.ChatOut = new System.Windows.Forms.TextBox();
- this.btnConnect = new System.Windows.Forms.Button();
- this.btnDisconnect = new System.Windows.Forms.Button();
- this.btnLog = new System.Windows.Forms.Button();
- this.cbPrivate = new System.Windows.Forms.CheckBox();
- this.btnSend = new System.Windows.Forms.Button();
- this.statusBar1 = new System.Windows.Forms.StatusBar();
- this.lbChatters = new System.Windows.Forms.ListBox();
- this.rtbChatIn = new System.Windows.Forms.RichTextBox();
- this.SuspendLayout();
- //
- // ChatOut
- //
- this.ChatOut.Location = new System.Drawing.Point(168, 296);
- this.ChatOut.Name = "ChatOut";
- this.ChatOut.Size = new System.Drawing.Size(248, 21);
- this.ChatOut.TabIndex = 2;
- this.ChatOut.Text = "";
- //
- // btnConnect
- //
- this.btnConnect.FlatStyle = System.Windows.Forms.FlatStyle.Flat;
- this.btnConnect.Location = new System.Drawing.Point(40, 192);
- this.btnConnect.Name = "btnConnect";
- this.btnConnect.Size = new System.Drawing.Size(75, 24);
- this.btnConnect.TabIndex = 3;
- this.btnConnect.Text = "连接";
- this.btnConnect.MouseUp += new System.Windows.Forms.MouseEventHandler(this.btnConnect_MouseUp);
- //
- // btnDisconnect
- //
- this.btnDisconnect.FlatStyle = System.Windows.Forms.FlatStyle.Flat;
- this.btnDisconnect.Location = new System.Drawing.Point(40, 224);
- this.btnDisconnect.Name = "btnDisconnect";
- this.btnDisconnect.Size = new System.Drawing.Size(75, 24);
- this.btnDisconnect.TabIndex = 4;
- this.btnDisconnect.Text = "断开连接";
- this.btnDisconnect.MouseUp += new System.Windows.Forms.MouseEventHandler(this.btnDisconnect_MouseUp);
- //
- // btnLog
- //
- this.btnLog.FlatStyle = System.Windows.Forms.FlatStyle.Flat;
- this.btnLog.Location = new System.Drawing.Point(40, 256);
- this.btnLog.Name = "btnLog";
- this.btnLog.Size = new System.Drawing.Size(75, 24);
- this.btnLog.TabIndex = 5;
- this.btnLog.Text = "开始记录";
- this.btnLog.MouseUp += new System.Windows.Forms.MouseEventHandler(this.btnLog_MouseUp);
- //
- // cbPrivate
- //
- this.cbPrivate.FlatStyle = System.Windows.Forms.FlatStyle.Flat;
- this.cbPrivate.Location = new System.Drawing.Point(48, 288);
- this.cbPrivate.Name = "cbPrivate";
- this.cbPrivate.Size = new System.Drawing.Size(64, 32);
- this.cbPrivate.TabIndex = 6;
- this.cbPrivate.Text = "悄悄话";
- this.cbPrivate.CheckedChanged += new System.EventHandler(this.cbPrivate_CheckedChanged);
- //
- // btnSend
- //
- this.btnSend.FlatStyle = System.Windows.Forms.FlatStyle.Flat;
- this.btnSend.Location = new System.Drawing.Point(432, 296);
- this.btnSend.Name = "btnSend";
- this.btnSend.Size = new System.Drawing.Size(48, 24);
- this.btnSend.TabIndex = 7;
- this.btnSend.Text = "发送";
- this.btnSend.MouseUp += new System.Windows.Forms.MouseEventHandler(this.btnSend_MouseUp);
- //
- // statusBar1
- //
- this.statusBar1.Location = new System.Drawing.Point(0, 335);
- this.statusBar1.Name = "statusBar1";
- this.statusBar1.Size = new System.Drawing.Size(496, 22);
- this.statusBar1.TabIndex = 8;
- //
- // lbChatters
- //
- this.lbChatters.ItemHeight = 12;
- this.lbChatters.Location = new System.Drawing.Point(16, 32);
- this.lbChatters.Name = "lbChatters";
- this.lbChatters.Size = new System.Drawing.Size(128, 148);
- this.lbChatters.TabIndex = 0;
- //
- // rtbChatIn
- //
- this.rtbChatIn.Location = new System.Drawing.Point(168, 32);
- this.rtbChatIn.Name = "rtbChatIn";
- this.rtbChatIn.Size = new System.Drawing.Size(312, 248);
- this.rtbChatIn.TabIndex = 1;
- this.rtbChatIn.Text = "";
- //
- // Form1
- //
- this.AutoScaleBaseSize = new System.Drawing.Size(6, 14);
- this.ClientSize = new System.Drawing.Size(496, 357);
- this.Controls.AddRange(new System.Windows.Forms.Control[] {
- this.rtbChatIn,
- this.lbChatters,
- this.statusBar1,
- this.btnSend,
- this.cbPrivate,
- this.btnLog,
- this.btnDisconnect,
- this.btnConnect,
- this.ChatOut});
- this.Name = "Form1";
- this.Text = "客户端";
- this.ResumeLayout(false);
- }
- #endregion
- private void EstablishConnection()
- {
- statusBar1.Text = "正在连接到服务器";
- try
- {
- clientsocket = new TcpClient(serveraddress,serverport);
- ns = clientsocket.GetStream();
- sr = new StreamReader(ns);
- connected = true;
- }
- catch (Exception)
- {
- MessageBox.Show("不能连接到服务器!","错误",
- MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
- statusBar1.Text = "已断开连接";
- }
- }
- private void RegisterWithServer()
- {
- try
- {
- string command = "CONN|" + ChatOut.Text;
- 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(new Char[]{'|'});
- if(tokens[0] == "LIST")
- {
- statusBar1.Text = "已连接";
- btnDisconnect.Enabled = true;
- }
- for(int n=1; n<tokens.Length-1; n++)
- lbChatters.Items.Add(tokens[n].Trim(new char[]{'r','n'}));
- this.Text = clientname + ":已连接到服务器";
- }
- catch (Exception)
- {
- MessageBox.Show("注册时发生错误!","错误",
- MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
- }
- }
- private void ReceiveChat()
- {
- bool keepalive = true;
- while (keepalive)
- {
- try
- {
- Byte[] buffer = new Byte[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")
- {
- rtbChatIn.AppendText(tokens[1]);
- if(logging)
- logwriter.WriteLine(tokens[1]);
- }
- if (tokens[0] == "PRIV")
- {
- rtbChatIn.AppendText("Private from ");
- rtbChatIn.AppendText(tokens[1].Trim() );
- rtbChatIn.AppendText(tokens[2] + "rn");
- if(logging)
- {
- logwriter.Write("Private from ");
- logwriter.Write(tokens[1].Trim() );
- logwriter.WriteLine(tokens[2] + "rn");
- }
- }
- if (tokens[0] == "JOIN")
- {
- rtbChatIn.AppendText(tokens[1].Trim() );
- rtbChatIn.AppendText(" has joined the Chatrn");
- if(logging)
- {
- logwriter.WriteLine(tokens[1]+" has joined the Chat");
- }
- string newguy = tokens[1].Trim(new char[]{'r','n'});
- lbChatters.Items.Add(newguy);
- }
- if (tokens[0] == "GONE")
- {
- rtbChatIn.AppendText(tokens[1].Trim() );
- rtbChatIn.AppendText(" has left the Chatrn");
- if(logging)
- {
- logwriter.WriteLine(tokens[1]+" has left the Chat");
- }
- lbChatters.Items.Remove(tokens[1].Trim(new char[]{'r','n'}));
- }
- if (tokens[0] == "QUIT")
- {
- ns.Close();
- clientsocket.Close();
- keepalive = false;
- statusBar1.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)
- {
- }
- }
- if(logging)
- logwriter.Close();
- if(receive != null && receive.IsAlive)
- receive.Abort();
- this.Text = "客户端";
- }
- private void StartStopLogging()
- {
- if(!logging)
- {
- if(!Directory.Exists("logs"))
- Directory.CreateDirectory("logs");
- string fname = "logs\" + DateTime.Now.ToString("ddMMyyHHmm") + ".txt";
- logwriter = new StreamWriter(new FileStream(fname, FileMode.OpenOrCreate,
- FileAccess.Write));
- logging = true;
- btnLog.Text = "停止记录";
- statusBar1.Text = "已连接上并记录";
- }
- else
- {
- logwriter.Close();
- logging = false;
- btnLog.Text = "开始记录";
- statusBar1.Text = "已连接上但不记录";
- }
- }
- /// <summary>
- /// 应用程序的主入口点。
- /// </summary>
- [STAThread]
- static void Main(String[] args)
- {
- Form1 cf = new Form1();
- if(args.Length == 0)
- cf.serveraddress = "localhost";
- else
- cf.serveraddress = args[0];
- Application.Run(cf);
- }
- private void btnConnect_MouseUp(object sender, System.Windows.Forms.MouseEventArgs e)
- {
- if(ChatOut.Text == "")
- {
- MessageBox.Show("连接前请在消息发送框中写上你的大名!","错误",
- MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
- return;
- }
- else
- clientname = ChatOut.Text;
- EstablishConnection();
- if(connected)
- {
- RegisterWithServer();
- receive = new Thread(new ThreadStart(ReceiveChat));
- receive.Start();
- btnSend.Enabled = true;
- btnConnect.Enabled = false;
- ChatOut.Text = "";
- }
- }
- private void btnDisconnect_MouseUp(object sender, System.Windows.Forms.MouseEventArgs e)
- {
- QuitChat();
- btnDisconnect.Enabled = false;
- btnConnect.Enabled = true;
- btnSend.Enabled = false;
- ns.Close();
- clientsocket.Close();
- receive.Abort();
- connected = false;
- lbChatters.Items.Clear();
- statusBar1.Text = "已断开连接";
- }
- private void btnLog_MouseUp(object sender, System.Windows.Forms.MouseEventArgs e)
- {
- StartStopLogging();
- }
- private void btnSend_MouseUp(object sender, System.Windows.Forms.MouseEventArgs e)
- {
- try
- {
- if(!privatemode)
- {
- string pubcommand = "CHAT|" + clientname +": "+ChatOut.Text + "rn";
- Byte[] outbytes = System.Text.Encoding.ASCII.GetBytes(pubcommand.ToCharArray());
- ns.Write(outbytes,0,outbytes.Length);
- ChatOut.Text = "";
- }
- else
- {
- if(lbChatters.SelectedIndex == -1)
- {
- MessageBox.Show("请从列表中选择一个对象!","错误",
- MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
- return;
- }
- string destclient = lbChatters.SelectedItem.ToString();
- string command = "PRIV|" + clientname + "|: " + ChatOut.Text + "|" + destclient;
- Byte[] outbytes = System.Text.Encoding.ASCII.GetBytes(command.ToCharArray());
- ns.Write(outbytes,0,outbytes.Length);
- ChatOut.Text = "";
- }
- }
- catch(Exception)
- {
- MessageBox.Show("到服务器的连接丢失!","错误",
- MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
- ns.Close();
- clientsocket.Close();
- if(receive != null && receive.IsAlive)
- receive.Abort();
- connected = false;
- statusBar1.Text = "已断开连接";
- }
- }
- private void cbPrivate_CheckedChanged(object sender, System.EventArgs e)
- {
- if(cbPrivate.Checked)
- {
- privatemode = true;
- lbChatters.SelectionMode = System.Windows.Forms.SelectionMode.One;
- }
- else
- {
- privatemode = false;
- lbChatters.SelectionMode = System.Windows.Forms.SelectionMode.None;
- }
- }
- }
- }