📄 frmchatclient.cs
字号:
using System;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
using System.Data;
using System.Net;
using System.Net.Sockets;
using System.Threading;
using System.Text;
using System.IO;
namespace WindowsApplication2
{
/// <summary>
/// Form1 的摘要说明。
/// </summary>
public class frmChatClient : System.Windows.Forms.Form
{
private string clientname="";
private int serverport;
private NetworkStream ns;
//private StreamReader sr;
private TcpClient clientsocket;
private Thread receive=null;
private string serveraddress;
private bool connected=false;
//private bool logging=false;
private bool privatemode=false;
private System.Windows.Forms.TextBox txtChatOut;
private System.Windows.Forms.ListBox lstChatters;
private System.Windows.Forms.Button btnSend;
private System.Windows.Forms.Button btnConnect;
private System.Windows.Forms.Button btnDisconnect;
private System.Windows.Forms.Button btnLog;
private System.Windows.Forms.CheckBox chkPrivate;
private System.Windows.Forms.Button btnSet;
private System.Windows.Forms.TextBox txtChatIn;
/// <summary>
/// 必需的设计器变量。
/// </summary>
private System.ComponentModel.Container components = null;
public frmChatClient()
{
//
// Windows 窗体设计器支持所必需的
//
InitializeComponent();
//
// TODO: 在 InitializeComponent 调用后添加任何构造函数代码
//
}
/// <summary>
/// 清理所有正在使用的资源。
/// </summary>
protected override void Dispose( bool disposing )
{
if( disposing )
{
if (components != null)
{
components.Dispose();
}
}
base.Dispose( disposing );
}
#region Windows 窗体设计器生成的代码
/// <summary>
/// 设计器支持所需的方法 - 不要使用代码编辑器修改
/// 此方法的内容。
/// </summary>
private void InitializeComponent()
{
this.txtChatOut = new System.Windows.Forms.TextBox();
this.lstChatters = new System.Windows.Forms.ListBox();
this.btnSend = new System.Windows.Forms.Button();
this.btnConnect = new System.Windows.Forms.Button();
this.btnDisconnect = new System.Windows.Forms.Button();
this.btnLog = new System.Windows.Forms.Button();
this.chkPrivate = new System.Windows.Forms.CheckBox();
this.btnSet = new System.Windows.Forms.Button();
this.txtChatIn = new System.Windows.Forms.TextBox();
this.SuspendLayout();
//
// txtChatOut
//
this.txtChatOut.Location = new System.Drawing.Point(8, 216);
this.txtChatOut.Name = "txtChatOut";
this.txtChatOut.Size = new System.Drawing.Size(272, 21);
this.txtChatOut.TabIndex = 1;
this.txtChatOut.Text = "";
this.txtChatOut.KeyPress += new System.Windows.Forms.KeyPressEventHandler(this.txtChatOut_KeyPress);
//
// lstChatters
//
this.lstChatters.ItemHeight = 12;
this.lstChatters.Location = new System.Drawing.Point(288, 8);
this.lstChatters.Name = "lstChatters";
this.lstChatters.Size = new System.Drawing.Size(112, 196);
this.lstChatters.TabIndex = 2;
//
// btnSend
//
this.btnSend.Enabled = false;
this.btnSend.Location = new System.Drawing.Point(296, 216);
this.btnSend.Name = "btnSend";
this.btnSend.Size = new System.Drawing.Size(80, 23);
this.btnSend.TabIndex = 3;
this.btnSend.Text = "发送(Enter)";
this.btnSend.Click += new System.EventHandler(this.btnSend_Click);
//
// btnConnect
//
this.btnConnect.Location = new System.Drawing.Point(408, 8);
this.btnConnect.Name = "btnConnect";
this.btnConnect.Size = new System.Drawing.Size(80, 23);
this.btnConnect.TabIndex = 4;
this.btnConnect.Text = "连接(&C)";
this.btnConnect.Click += new System.EventHandler(this.btnConnect_Click);
//
// btnDisconnect
//
this.btnDisconnect.Location = new System.Drawing.Point(408, 40);
this.btnDisconnect.Name = "btnDisconnect";
this.btnDisconnect.Size = new System.Drawing.Size(80, 23);
this.btnDisconnect.TabIndex = 5;
this.btnDisconnect.Text = "断开连接(&D)";
this.btnDisconnect.Click += new System.EventHandler(this.btnDisconnect_Click);
//
// btnLog
//
this.btnLog.Location = new System.Drawing.Point(408, 72);
this.btnLog.Name = "btnLog";
this.btnLog.Size = new System.Drawing.Size(80, 23);
this.btnLog.TabIndex = 6;
this.btnLog.Text = "记录日志(&L)";
//
// chkPrivate
//
this.chkPrivate.Location = new System.Drawing.Point(424, 104);
this.chkPrivate.Name = "chkPrivate";
this.chkPrivate.Size = new System.Drawing.Size(56, 24);
this.chkPrivate.TabIndex = 7;
this.chkPrivate.Text = "私聊";
//
// btnSet
//
this.btnSet.Location = new System.Drawing.Point(408, 168);
this.btnSet.Name = "btnSet";
this.btnSet.TabIndex = 8;
this.btnSet.Text = "设置(&S)";
this.btnSet.Click += new System.EventHandler(this.btnSet_Click);
//
// txtChatIn
//
this.txtChatIn.BackColor = System.Drawing.Color.White;
this.txtChatIn.Location = new System.Drawing.Point(8, 8);
this.txtChatIn.Multiline = true;
this.txtChatIn.Name = "txtChatIn";
this.txtChatIn.ReadOnly = true;
this.txtChatIn.ScrollBars = System.Windows.Forms.ScrollBars.Vertical;
this.txtChatIn.Size = new System.Drawing.Size(272, 195);
this.txtChatIn.TabIndex = 9;
this.txtChatIn.Text = "";
this.txtChatIn.TextChanged += new System.EventHandler(this.txtChatIn_TextChanged);
//
// frmChatClient
//
this.AutoScaleBaseSize = new System.Drawing.Size(6, 14);
this.ClientSize = new System.Drawing.Size(496, 269);
this.Controls.Add(this.txtChatIn);
this.Controls.Add(this.btnSet);
this.Controls.Add(this.chkPrivate);
this.Controls.Add(this.btnLog);
this.Controls.Add(this.btnDisconnect);
this.Controls.Add(this.btnConnect);
this.Controls.Add(this.btnSend);
this.Controls.Add(this.lstChatters);
this.Controls.Add(this.txtChatOut);
this.MaximizeBox = false;
this.MaximumSize = new System.Drawing.Size(504, 303);
this.Name = "frmChatClient";
this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen;
this.Text = "客户聊天程序";
this.Closing += new System.ComponentModel.CancelEventHandler(this.frmChatClient_Closing);
this.Load += new System.EventHandler(this.frmChatClient_Load);
this.ResumeLayout(false);
}
#endregion
/// <summary>
/// 应用程序的主入口点。
/// </summary>
[STAThread]
static void Main()
{
Application.Run(new frmChatClient());
}
private void btnSend_Click(object sender, System.EventArgs e)
{
try
{
if(chkPrivate.Checked)
{
privatemode=true;
}
else
{
privatemode=false;
}
if(!privatemode)
{
string pubcommand="CHAT|"+clientname+":"+txtChatOut.Text+"\r\n";
Byte[] outbytes=System.Text.Encoding.GetEncoding("gb2312").GetBytes(pubcommand.ToCharArray());
ns.Write(outbytes,0,outbytes.Length);
txtChatOut.Clear();
txtChatOut.Focus();
}
else
{
if(lstChatters.SelectedIndex==-1)
{
MessageBox.Show("请从列表中选择一个名字","Error",MessageBoxButtons.OK,
MessageBoxIcon.Exclamation);
return;
}
string destclient=lstChatters.SelectedItem.ToString();
string command="PRIV|"+clientname+"|:"+txtChatOut.Text+"|"+destclient;
Byte[] outbytes=System.Text.Encoding.GetEncoding("gb2312").GetBytes(command.ToCharArray());
ns.Write(outbytes,0,outbytes.Length);
txtChatOut.Clear();
txtChatOut.Focus();
}
}
catch(Exception ex)
{
MessageBox.Show("与服务器失去连接"+ex.Message,"Error",MessageBoxButtons.OK,MessageBoxIcon.Exclamation);
ns.Close();
clientsocket.Close();
if(receive!=null && receive.IsAlive)
receive.Abort();
connected=false;
}
}
private void btnConnect_Click(object sender, System.EventArgs e)
{
if(txtChatOut.Text.Length==0)
{
MessageBox.Show("在连接前请先输入姓名","Error",MessageBoxButtons.OK,MessageBoxIcon.Exclamation);
return;
}
else
clientname=txtChatOut.Text;
EstablishConnection();
if(connected)
{
RegisterWithServer();
receive=new Thread(new ThreadStart(ReceiveChat));
receive.Start();
btnSend.Enabled=true;
btnConnect.Enabled=false;
btnDisconnect.Enabled=true;
txtChatOut.Clear();
}
}
private void EstablishConnection()
{
try
{
clientsocket=new TcpClient(serveraddress,serverport);
ns=clientsocket.GetStream();
string command="CONN|"+clientname;
Byte[] buffer=System.Text.Encoding.GetEncoding("gb2312").GetBytes(command.ToCharArray());
ns.Write(buffer,0,buffer.Length);
connected=true;
}
catch(Exception ex)
{
ns.Close();
clientsocket.Close();
connected=false;
MessageBox.Show(ex.Message);
}
}
private void RegisterWithServer()
{
}
private void ReceiveChat()
{
while(true)
{
if(ns.CanRead)
{
Byte[] chatIn=new Byte[1024];
ns.Read(chatIn,0,chatIn.Length);
string command=System.Text.Encoding.GetEncoding("gb2312").GetString(chatIn);
string[] tokens=command.Split(new Char[]{'|'});
if(tokens[0].Equals("LIST"))//聊天者清单
{
lstChatters.Items.Clear();
for(int i=1;i<tokens.Length-1;i++)
{
string chatterName=tokens[i];
lstChatters.Items.Add(chatterName);
}
}
else if(tokens[0].Equals("CHAT"))//消息
{
txtChatIn.AppendText(tokens[1]);
}
else if(tokens[0].Equals("PRIV"))
{
txtChatIn.AppendText("(私聊)"+tokens[1]+tokens[2]+"\r\n");
}
else if(tokens[0].Equals("JOIN"))//聊天者加入
{
lstChatters.Items.Add(tokens[1]);
string message=tokens[1].Trim(new Char[]{'\0'})+"加入了."+"\r\n";
txtChatIn.AppendText(message);
}
else if(tokens[0].Equals("GONE"))//有人退出聊天
{
lstChatters.Items.Remove(tokens[1]);
string message=tokens[1].Trim(new Char[]{'\0'})+"退出了."+"\r\n";
txtChatIn.AppendText(message);
}
}
}
}
private void btnDisconnect_Click(object sender, System.EventArgs e)
{
QuitChat();
btnDisconnect.Enabled=false;
btnConnect.Enabled=true;
btnSend.Enabled=false;
ns.Close();
clientsocket.Close();
receive.Abort();
connected=false;
lstChatters.Items.Clear();
}
private void QuitChat()
{
string command="GONE|"+clientname;
Byte[] buffer=System.Text.Encoding.GetEncoding("gb2312").GetBytes(command.ToCharArray());
ns.Write(buffer,0,buffer.Length);
}
private void frmChatClient_Load(object sender, System.EventArgs e)
{
serveraddress="127.0.0.1";
serverport=0228;
}
private void frmChatClient_Closing(object sender, System.ComponentModel.CancelEventArgs e)
{
if(connected)
{
btnDisconnect_Click(sender,e);
}
}
private void btnSet_Click(object sender, System.EventArgs e)
{
frmSetServerIP objfrm=new frmSetServerIP();
if(objfrm.ShowDialog()==DialogResult.OK)
{
serveraddress=objfrm.ServerAddress;
}
}
private void txtChatIn_TextChanged(object sender, System.EventArgs e)
{
txtChatIn.ScrollToCaret();
}
private void txtChatOut_KeyPress(object sender, System.Windows.Forms.KeyPressEventArgs e)
{
if(btnSend.Enabled)
{
if(e.KeyChar==13)
{
btnSend_Click(sender,e);
}
}
}
}
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -