Form1.cs
上传用户:yiyuerguo
上传日期:2014-09-27
资源大小:3781k
文件大小:13k
源码类别:

C#编程

开发平台:

Others

  1. using System;
  2. using System.Drawing;
  3. using System.Collections;
  4. using System.ComponentModel;
  5. using System.Windows.Forms;
  6. using System.Data;
  7. using System.Net.Sockets;
  8. using System.IO;
  9. using System.Threading;
  10. using System.Text;
  11. namespace ChatClient
  12. {
  13. /// <summary>
  14. /// Form1 的摘要说明。
  15. /// </summary>
  16. public class Form1 : System.Windows.Forms.Form
  17. {
  18. private System.Windows.Forms.StatusBar statusBar1;
  19. private System.Windows.Forms.Button btnDisconnect;
  20. private System.Windows.Forms.Button btnConnect;
  21. private System.Windows.Forms.Button btnLog;
  22. private System.Windows.Forms.CheckBox cbPrivate;
  23. private System.Windows.Forms.Button btnSend;
  24. private System.Windows.Forms.TextBox ChatOut;
  25. private System.Windows.Forms.RichTextBox rtbChatIn;
  26. private System.Windows.Forms.ListBox lbChatters;
  27. private int serverport;
  28. private NetworkStream ns;
  29. private StreamReader sr;
  30. private TcpClient clientsocket;
  31. private Thread receive = null;
  32. private string serveraddress;
  33. private string clientname;
  34. private bool connected = false;
  35. private bool logging = false;
  36. private bool privatemode = false;
  37. private StreamWriter logwriter;
  38. /// <summary>
  39. /// 必需的设计器变量。
  40. /// </summary>
  41. private System.ComponentModel.Container components = null;
  42. public Form1()
  43. {
  44. //
  45. // Windows 窗体设计器支持所必需的
  46. //
  47. InitializeComponent();
  48. //
  49. // TODO: 在 InitializeComponent 调用后添加任何构造函数代码
  50. //
  51. serverport = 5555;
  52. btnDisconnect.Enabled = false;
  53. btnSend.Enabled = false;
  54. }
  55. /// <summary>
  56. /// 清理所有正在使用的资源。
  57. /// </summary>
  58. protected override void Dispose( bool disposing )
  59. {
  60. if( disposing )
  61. {
  62. if (components != null) 
  63. {
  64. components.Dispose();
  65. }
  66. }
  67. base.Dispose( disposing );
  68. }
  69. #region Windows Form Designer generated code
  70. /// <summary>
  71. /// 设计器支持所需的方法 - 不要使用代码编辑器修改
  72. /// 此方法的内容。
  73. /// </summary>
  74. private void InitializeComponent()
  75. {
  76. this.ChatOut = new System.Windows.Forms.TextBox();
  77. this.btnConnect = new System.Windows.Forms.Button();
  78. this.btnDisconnect = new System.Windows.Forms.Button();
  79. this.btnLog = new System.Windows.Forms.Button();
  80. this.cbPrivate = new System.Windows.Forms.CheckBox();
  81. this.btnSend = new System.Windows.Forms.Button();
  82. this.statusBar1 = new System.Windows.Forms.StatusBar();
  83. this.lbChatters = new System.Windows.Forms.ListBox();
  84. this.rtbChatIn = new System.Windows.Forms.RichTextBox();
  85. this.SuspendLayout();
  86. // 
  87. // ChatOut
  88. // 
  89. this.ChatOut.Location = new System.Drawing.Point(168, 296);
  90. this.ChatOut.Name = "ChatOut";
  91. this.ChatOut.Size = new System.Drawing.Size(248, 21);
  92. this.ChatOut.TabIndex = 2;
  93. this.ChatOut.Text = "";
  94. // 
  95. // btnConnect
  96. // 
  97. this.btnConnect.FlatStyle = System.Windows.Forms.FlatStyle.Flat;
  98. this.btnConnect.Location = new System.Drawing.Point(40, 192);
  99. this.btnConnect.Name = "btnConnect";
  100. this.btnConnect.Size = new System.Drawing.Size(75, 24);
  101. this.btnConnect.TabIndex = 3;
  102. this.btnConnect.Text = "连接";
  103. this.btnConnect.MouseUp += new System.Windows.Forms.MouseEventHandler(this.btnConnect_MouseUp);
  104. // 
  105. // btnDisconnect
  106. // 
  107. this.btnDisconnect.FlatStyle = System.Windows.Forms.FlatStyle.Flat;
  108. this.btnDisconnect.Location = new System.Drawing.Point(40, 224);
  109. this.btnDisconnect.Name = "btnDisconnect";
  110. this.btnDisconnect.Size = new System.Drawing.Size(75, 24);
  111. this.btnDisconnect.TabIndex = 4;
  112. this.btnDisconnect.Text = "断开连接";
  113. this.btnDisconnect.MouseUp += new System.Windows.Forms.MouseEventHandler(this.btnDisconnect_MouseUp);
  114. // 
  115. // btnLog
  116. // 
  117. this.btnLog.FlatStyle = System.Windows.Forms.FlatStyle.Flat;
  118. this.btnLog.Location = new System.Drawing.Point(40, 256);
  119. this.btnLog.Name = "btnLog";
  120. this.btnLog.Size = new System.Drawing.Size(75, 24);
  121. this.btnLog.TabIndex = 5;
  122. this.btnLog.Text = "开始记录";
  123. this.btnLog.MouseUp += new System.Windows.Forms.MouseEventHandler(this.btnLog_MouseUp);
  124. // 
  125. // cbPrivate
  126. // 
  127. this.cbPrivate.FlatStyle = System.Windows.Forms.FlatStyle.Flat;
  128. this.cbPrivate.Location = new System.Drawing.Point(48, 288);
  129. this.cbPrivate.Name = "cbPrivate";
  130. this.cbPrivate.Size = new System.Drawing.Size(64, 32);
  131. this.cbPrivate.TabIndex = 6;
  132. this.cbPrivate.Text = "悄悄话";
  133. this.cbPrivate.CheckedChanged += new System.EventHandler(this.cbPrivate_CheckedChanged);
  134. // 
  135. // btnSend
  136. // 
  137. this.btnSend.FlatStyle = System.Windows.Forms.FlatStyle.Flat;
  138. this.btnSend.Location = new System.Drawing.Point(432, 296);
  139. this.btnSend.Name = "btnSend";
  140. this.btnSend.Size = new System.Drawing.Size(48, 24);
  141. this.btnSend.TabIndex = 7;
  142. this.btnSend.Text = "发送";
  143. this.btnSend.MouseUp += new System.Windows.Forms.MouseEventHandler(this.btnSend_MouseUp);
  144. // 
  145. // statusBar1
  146. // 
  147. this.statusBar1.Location = new System.Drawing.Point(0, 335);
  148. this.statusBar1.Name = "statusBar1";
  149. this.statusBar1.Size = new System.Drawing.Size(496, 22);
  150. this.statusBar1.TabIndex = 8;
  151. // 
  152. // lbChatters
  153. // 
  154. this.lbChatters.ItemHeight = 12;
  155. this.lbChatters.Location = new System.Drawing.Point(16, 32);
  156. this.lbChatters.Name = "lbChatters";
  157. this.lbChatters.Size = new System.Drawing.Size(128, 148);
  158. this.lbChatters.TabIndex = 0;
  159. // 
  160. // rtbChatIn
  161. // 
  162. this.rtbChatIn.Location = new System.Drawing.Point(168, 32);
  163. this.rtbChatIn.Name = "rtbChatIn";
  164. this.rtbChatIn.Size = new System.Drawing.Size(312, 248);
  165. this.rtbChatIn.TabIndex = 1;
  166. this.rtbChatIn.Text = "";
  167. // 
  168. // Form1
  169. // 
  170. this.AutoScaleBaseSize = new System.Drawing.Size(6, 14);
  171. this.ClientSize = new System.Drawing.Size(496, 357);
  172. this.Controls.AddRange(new System.Windows.Forms.Control[] {
  173.   this.rtbChatIn,
  174.   this.lbChatters,
  175.   this.statusBar1,
  176.   this.btnSend,
  177.   this.cbPrivate,
  178.   this.btnLog,
  179.   this.btnDisconnect,
  180.   this.btnConnect,
  181.   this.ChatOut});
  182. this.Name = "Form1";
  183. this.Text = "客户端";
  184. this.ResumeLayout(false);
  185. }
  186. #endregion
  187. private void EstablishConnection()
  188. {
  189. statusBar1.Text = "正在连接到服务器";
  190. try 
  191. {
  192. clientsocket = new TcpClient(serveraddress,serverport);
  193. ns = clientsocket.GetStream();
  194. sr = new StreamReader(ns);
  195. connected = true;
  196. }
  197. catch (Exception)
  198. {
  199. MessageBox.Show("不能连接到服务器!","错误",
  200. MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
  201. statusBar1.Text = "已断开连接";
  202. }
  203. }
  204. private void RegisterWithServer()
  205. {
  206. try 
  207. {
  208. string command = "CONN|" + ChatOut.Text;
  209. Byte[] outbytes = System.Text.Encoding.ASCII.GetBytes(command.ToCharArray());
  210. ns.Write(outbytes,0,outbytes.Length);
  211. string serverresponse = sr.ReadLine();
  212. serverresponse.Trim();
  213. string[] tokens = serverresponse.Split(new Char[]{'|'});
  214. if(tokens[0] == "LIST")
  215. {
  216. statusBar1.Text = "已连接";
  217. btnDisconnect.Enabled = true;
  218. }
  219. for(int n=1; n<tokens.Length-1; n++)
  220. lbChatters.Items.Add(tokens[n].Trim(new char[]{'r','n'}));
  221. this.Text = clientname + ":已连接到服务器";
  222. }
  223. catch (Exception)
  224. {
  225. MessageBox.Show("注册时发生错误!","错误",
  226. MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
  227. }
  228. }
  229. private void ReceiveChat()
  230. {
  231. bool keepalive = true;
  232. while (keepalive) 
  233. {
  234. try
  235. {
  236. Byte[] buffer = new Byte[2048];
  237. ns.Read(buffer,0,buffer.Length);
  238. string chatter = System.Text.Encoding.ASCII.GetString(buffer);
  239. string[] tokens = chatter.Split(new Char[]{'|'});
  240. if (tokens[0] == "CHAT")
  241. {
  242. rtbChatIn.AppendText(tokens[1]);
  243. if(logging)
  244. logwriter.WriteLine(tokens[1]);
  245. }
  246. if (tokens[0] == "PRIV") 
  247. {
  248. rtbChatIn.AppendText("Private from ");
  249. rtbChatIn.AppendText(tokens[1].Trim() );
  250. rtbChatIn.AppendText(tokens[2] + "rn");
  251. if(logging)
  252. {
  253. logwriter.Write("Private from ");
  254. logwriter.Write(tokens[1].Trim() );
  255. logwriter.WriteLine(tokens[2] + "rn");
  256. }
  257. }
  258. if (tokens[0] == "JOIN")
  259. {
  260. rtbChatIn.AppendText(tokens[1].Trim() );
  261. rtbChatIn.AppendText(" has joined the Chatrn");
  262. if(logging)
  263. {
  264. logwriter.WriteLine(tokens[1]+" has joined the Chat");
  265. }
  266. string newguy = tokens[1].Trim(new char[]{'r','n'});
  267. lbChatters.Items.Add(newguy);
  268. }
  269. if (tokens[0] == "GONE")
  270. {
  271. rtbChatIn.AppendText(tokens[1].Trim() );
  272. rtbChatIn.AppendText(" has left the Chatrn");
  273. if(logging)
  274. {
  275. logwriter.WriteLine(tokens[1]+" has left the Chat");
  276. }
  277. lbChatters.Items.Remove(tokens[1].Trim(new char[]{'r','n'}));
  278. }
  279. if (tokens[0] == "QUIT")
  280. {
  281. ns.Close();
  282. clientsocket.Close();
  283. keepalive = false;
  284. statusBar1.Text = "服务器端已停止";
  285. connected= false;
  286. btnSend.Enabled = false;
  287. btnDisconnect.Enabled = false;
  288. }
  289. }
  290. catch(Exception){}
  291. }
  292. }
  293. private void QuitChat() 
  294. {
  295. if(connected) 
  296. {
  297. try
  298. {
  299. string command = "GONE|" + clientname;
  300. Byte[] outbytes = System.Text.Encoding.ASCII.GetBytes(command.ToCharArray());
  301. ns.Write(outbytes,0,outbytes.Length);
  302. clientsocket.Close();
  303. }
  304. catch(Exception)
  305. {
  306. }
  307. }
  308. if(logging)
  309. logwriter.Close();
  310. if(receive != null && receive.IsAlive)
  311. receive.Abort();
  312. this.Text = "客户端";
  313. }
  314. private void StartStopLogging() 
  315. {
  316. if(!logging)
  317. {
  318. if(!Directory.Exists("logs"))
  319. Directory.CreateDirectory("logs");
  320. string fname = "logs\" + DateTime.Now.ToString("ddMMyyHHmm") + ".txt";
  321. logwriter = new StreamWriter(new FileStream(fname, FileMode.OpenOrCreate,
  322. FileAccess.Write));
  323. logging = true;
  324. btnLog.Text = "停止记录";
  325. statusBar1.Text = "已连接上并记录";
  326. }
  327. else
  328. {
  329. logwriter.Close();
  330. logging = false;
  331. btnLog.Text = "开始记录";
  332. statusBar1.Text = "已连接上但不记录";
  333. }
  334. }
  335. /// <summary>
  336. /// 应用程序的主入口点。
  337. /// </summary>
  338. [STAThread]
  339. static void Main(String[] args) 
  340. {
  341. Form1 cf = new Form1();
  342. if(args.Length == 0)
  343. cf.serveraddress = "localhost";
  344. else
  345. cf.serveraddress = args[0];
  346. Application.Run(cf);
  347. }
  348. private void btnConnect_MouseUp(object sender, System.Windows.Forms.MouseEventArgs e)
  349. {
  350. if(ChatOut.Text == "")
  351. {
  352. MessageBox.Show("连接前请在消息发送框中写上你的大名!","错误",
  353. MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
  354. return;
  355. }
  356. else
  357. clientname = ChatOut.Text;
  358. EstablishConnection();
  359. if(connected)
  360. {
  361. RegisterWithServer();
  362. receive = new Thread(new ThreadStart(ReceiveChat));
  363. receive.Start();
  364. btnSend.Enabled = true;
  365. btnConnect.Enabled = false;
  366. ChatOut.Text = "";
  367. }
  368. }
  369. private void btnDisconnect_MouseUp(object sender, System.Windows.Forms.MouseEventArgs e)
  370. {
  371. QuitChat();
  372. btnDisconnect.Enabled = false;
  373. btnConnect.Enabled = true;
  374. btnSend.Enabled = false;
  375. ns.Close();
  376. clientsocket.Close();
  377. receive.Abort();
  378. connected = false;
  379. lbChatters.Items.Clear();
  380. statusBar1.Text = "已断开连接";
  381. }
  382. private void btnLog_MouseUp(object sender, System.Windows.Forms.MouseEventArgs e)
  383. {
  384. StartStopLogging();
  385. }
  386. private void btnSend_MouseUp(object sender, System.Windows.Forms.MouseEventArgs e)
  387. {
  388. try
  389. {
  390. if(!privatemode)
  391. {
  392. string pubcommand = "CHAT|" + clientname +": "+ChatOut.Text + "rn";
  393. Byte[] outbytes = System.Text.Encoding.ASCII.GetBytes(pubcommand.ToCharArray());
  394. ns.Write(outbytes,0,outbytes.Length);
  395. ChatOut.Text = "";
  396. }
  397. else
  398. {
  399. if(lbChatters.SelectedIndex == -1)
  400. {
  401. MessageBox.Show("请从列表中选择一个对象!","错误",
  402. MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
  403. return;
  404. }
  405. string destclient = lbChatters.SelectedItem.ToString();
  406. string command = "PRIV|" + clientname + "|: " + ChatOut.Text + "|" + destclient;
  407. Byte[] outbytes = System.Text.Encoding.ASCII.GetBytes(command.ToCharArray());
  408. ns.Write(outbytes,0,outbytes.Length);
  409. ChatOut.Text = "";
  410. }
  411. }
  412. catch(Exception)
  413. {
  414. MessageBox.Show("到服务器的连接丢失!","错误",
  415. MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
  416. ns.Close();
  417. clientsocket.Close();
  418. if(receive != null && receive.IsAlive)
  419. receive.Abort();
  420. connected = false;
  421. statusBar1.Text = "已断开连接";
  422. }
  423. }
  424. private void cbPrivate_CheckedChanged(object sender, System.EventArgs e)
  425. {
  426. if(cbPrivate.Checked)
  427. {
  428. privatemode = true;
  429. lbChatters.SelectionMode = System.Windows.Forms.SelectionMode.One;
  430. }
  431. else
  432. {
  433. privatemode = false;
  434. lbChatters.SelectionMode = System.Windows.Forms.SelectionMode.None;
  435. }
  436. }
  437. }
  438. }