ChatClient2.cs
上传用户:kenve1
上传日期:2008-04-28
资源大小:35k
文件大小:14k
源码类别:

ICQ/即时通讯

开发平台:

C#

  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. /// Summary description for Form1.
  15. /// </summary>
  16. public class ChatClientForm : System.Windows.Forms.Form
  17. {
  18. private System.Windows.Forms.TextBox ChatOut;
  19. private System.Windows.Forms.StatusBar statusBar1;
  20. /// <summary>
  21. /// Required designer variable.
  22. /// </summary>
  23. private System.ComponentModel.Container components = null;
  24. private System.Windows.Forms.Button btnConnect;
  25. private System.Windows.Forms.Button btnSend;
  26. private int serverport;
  27. private NetworkStream ns;
  28. private StreamReader sr;
  29. private TcpClient clientsocket;
  30. private Thread receive = null;
  31. private string serveraddress;
  32. private System.Windows.Forms.ListBox lbChatters;
  33. private System.Windows.Forms.RichTextBox rtbChatIn;
  34. private System.Windows.Forms.Button btnDisconnect;
  35. private string clientname;
  36. //private string destclient;
  37. private bool connected = false;
  38. private bool logging = false;
  39. private bool privatemode = false;
  40. private System.Windows.Forms.Button btnLog;
  41. private System.Windows.Forms.CheckBox cbPrivate;
  42. private StreamWriter logwriter;
  43. public ChatClientForm()
  44. {
  45. //
  46. // Required for Windows Form Designer support
  47. //
  48. InitializeComponent();
  49. serverport = 5555;
  50. btnDisconnect.Enabled = false;
  51. btnSend.Enabled = false;
  52. }
  53. /// <summary>
  54. /// Clean up any resources being used.
  55. /// </summary>
  56. protected override void Dispose( bool disposing )
  57. {
  58. if( disposing )
  59. {
  60. if (components != null) 
  61. {
  62. components.Dispose();
  63. }
  64. }
  65. base.Dispose( disposing );
  66. }
  67. #region Windows Form Designer generated code
  68. /// <summary>
  69. /// Required method for Designer support - do not modify
  70. /// the contents of this method with the code editor.
  71. /// </summary>
  72. private void InitializeComponent()
  73. {
  74. this.cbPrivate = new System.Windows.Forms.CheckBox();
  75. this.btnLog = new System.Windows.Forms.Button();
  76. this.btnSend = new System.Windows.Forms.Button();
  77. this.lbChatters = new System.Windows.Forms.ListBox();
  78. this.ChatOut = new System.Windows.Forms.TextBox();
  79. this.btnConnect = new System.Windows.Forms.Button();
  80. this.rtbChatIn = new System.Windows.Forms.RichTextBox();
  81. this.statusBar1 = new System.Windows.Forms.StatusBar();
  82. this.btnDisconnect = new System.Windows.Forms.Button();
  83. this.SuspendLayout();
  84. // 
  85. // cbPrivate
  86. // 
  87. this.cbPrivate.Font = new System.Drawing.Font("Tahoma", 9.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((System.Byte)(0)));
  88. this.cbPrivate.Location = new System.Drawing.Point(384, 112);
  89. this.cbPrivate.Name = "cbPrivate";
  90. this.cbPrivate.Size = new System.Drawing.Size(64, 24);
  91. this.cbPrivate.TabIndex = 10;
  92. this.cbPrivate.Text = "Private";
  93. this.cbPrivate.CheckStateChanged += new System.EventHandler(this.cbPrivate_CheckedChanged);
  94. // 
  95. // btnLog
  96. // 
  97. this.btnLog.Location = new System.Drawing.Point(376, 80);
  98. this.btnLog.Name = "btnLog";
  99. this.btnLog.Size = new System.Drawing.Size(80, 24);
  100. this.btnLog.TabIndex = 9;
  101. this.btnLog.Text = "Start Logging";
  102. this.btnLog.Click += new System.EventHandler(this.btnLog_Click);
  103. // 
  104. // btnSend
  105. // 
  106. this.btnSend.Location = new System.Drawing.Point(264, 232);
  107. this.btnSend.Name = "btnSend";
  108. this.btnSend.Size = new System.Drawing.Size(64, 24);
  109. this.btnSend.TabIndex = 5;
  110. this.btnSend.Text = "Send";
  111. this.btnSend.Click += new System.EventHandler(this.btnSend_Click);
  112. // 
  113. // lbChatters
  114. // 
  115. this.lbChatters.Location = new System.Drawing.Point(272, 16);
  116. this.lbChatters.Name = "lbChatters";
  117. this.lbChatters.SelectionMode = System.Windows.Forms.SelectionMode.None;
  118. this.lbChatters.Size = new System.Drawing.Size(88, 212);
  119. this.lbChatters.TabIndex = 7;
  120. // 
  121. // ChatOut
  122. // 
  123. this.ChatOut.Font = new System.Drawing.Font("Tahoma", 9.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((System.Byte)(0)));
  124. this.ChatOut.Location = new System.Drawing.Point(8, 232);
  125. this.ChatOut.Name = "ChatOut";
  126. this.ChatOut.Size = new System.Drawing.Size(240, 23);
  127. this.ChatOut.TabIndex = 2;
  128. this.ChatOut.Text = "";
  129. this.ChatOut.KeyPress += new System.Windows.Forms.KeyPressEventHandler(this.ChatOut_KeyPress);
  130. // 
  131. // btnConnect
  132. // 
  133. this.btnConnect.Location = new System.Drawing.Point(376, 16);
  134. this.btnConnect.Name = "btnConnect";
  135. this.btnConnect.Size = new System.Drawing.Size(80, 24);
  136. this.btnConnect.TabIndex = 4;
  137. this.btnConnect.Text = "Connect";
  138. this.btnConnect.Click += new System.EventHandler(this.btnConnect_Click);
  139. // 
  140. // rtbChatIn
  141. // 
  142. this.rtbChatIn.Font = new System.Drawing.Font("Tahoma", 9.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((System.Byte)(0)));
  143. this.rtbChatIn.Location = new System.Drawing.Point(8, 16);
  144. this.rtbChatIn.Name = "rtbChatIn";
  145. this.rtbChatIn.ReadOnly = true;
  146. this.rtbChatIn.Size = new System.Drawing.Size(240, 212);
  147. this.rtbChatIn.TabIndex = 6;
  148. this.rtbChatIn.Text = "";
  149. // 
  150. // statusBar1
  151. // 
  152. this.statusBar1.Location = new System.Drawing.Point(0, 275);
  153. this.statusBar1.Name = "statusBar1";
  154. this.statusBar1.Size = new System.Drawing.Size(478, 16);
  155. this.statusBar1.SizingGrip = false;
  156. this.statusBar1.TabIndex = 3;
  157. this.statusBar1.Text = "Disconnected";
  158. // 
  159. // btnDisconnect
  160. // 
  161. this.btnDisconnect.Location = new System.Drawing.Point(376, 48);
  162. this.btnDisconnect.Name = "btnDisconnect";
  163. this.btnDisconnect.Size = new System.Drawing.Size(80, 24);
  164. this.btnDisconnect.TabIndex = 8;
  165. this.btnDisconnect.Text = "Disconnect";
  166. this.btnDisconnect.Click += new System.EventHandler(this.btnDisconnect_Click);
  167. // 
  168. // ChatClientForm
  169. // 
  170. this.AutoScaleBaseSize = new System.Drawing.Size(5, 13);
  171. this.ClientSize = new System.Drawing.Size(478, 291);
  172. this.Controls.AddRange(new System.Windows.Forms.Control[] {
  173.   this.cbPrivate,
  174.   this.btnLog,
  175.   this.btnDisconnect,
  176.   this.lbChatters,
  177.   this.rtbChatIn,
  178.   this.btnSend,
  179.   this.btnConnect,
  180.   this.statusBar1,
  181.   this.ChatOut});
  182. this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedSingle;
  183. this.Name = "ChatClientForm";
  184. this.Text = "ChatClient";
  185. this.ResumeLayout(false);
  186. }
  187. #endregion
  188. protected override void OnClosed(EventArgs e)
  189. {
  190. QuitChat();
  191. if(receive != null && receive.IsAlive)
  192. receive.Abort();
  193. base.OnClosed(e);
  194. }
  195. private void EstablishConnection()
  196. {
  197. statusBar1.Text = "Connecting to Server";
  198. try 
  199. {
  200. clientsocket = new TcpClient(serveraddress,serverport);
  201. ns = clientsocket.GetStream();
  202. sr = new StreamReader(ns);
  203. connected = true;
  204. }
  205. catch (Exception e)
  206. {
  207. MessageBox.Show("Could not connect to Server","Error",
  208. MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
  209. statusBar1.Text = "Disconnected";
  210. }
  211. }
  212. private void RegisterWithServer()
  213. {
  214. try 
  215. {
  216. string command = "CONN|" + ChatOut.Text;
  217. Byte[] outbytes = System.Text.Encoding.ASCII.GetBytes(command.ToCharArray());
  218. ns.Write(outbytes,0,outbytes.Length);
  219. string serverresponse = sr.ReadLine();
  220. serverresponse.Trim();
  221. string[] tokens = serverresponse.Split(new Char[]{'|'});
  222. if(tokens[0] == "LIST")
  223. {
  224. statusBar1.Text = "Connected";
  225. btnDisconnect.Enabled = true;
  226. }
  227. for(int n=1; n<tokens.Length-1; n++)
  228. lbChatters.Items.Add(tokens[n].Trim(new char[]{'r','n'}));
  229. this.Text = clientname + ": Connected to Chat Server";
  230. }
  231. catch (Exception e)
  232. {
  233. MessageBox.Show("Error Registering","Error",
  234. MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
  235. }
  236. }
  237. private void ReceiveChat()
  238. {
  239. bool keepalive = true;
  240. while (keepalive) 
  241. {
  242. try
  243. {
  244. Byte[] buffer = new Byte[2048];
  245. ns.Read(buffer,0,buffer.Length);
  246. string chatter = System.Text.Encoding.ASCII.GetString(buffer);
  247. string[] tokens = chatter.Split(new Char[]{'|'});
  248. if (tokens[0] == "CHAT")
  249. {
  250. rtbChatIn.AppendText(tokens[1]);
  251. if(logging)
  252. logwriter.WriteLine(tokens[1]);
  253. }
  254. if (tokens[0] == "PRIV") {
  255. rtbChatIn.AppendText("Private from ");
  256. rtbChatIn.AppendText(tokens[1].Trim() );
  257. rtbChatIn.AppendText(tokens[2] + "rn");
  258. if(logging){
  259. logwriter.Write("Private from ");
  260. logwriter.Write(tokens[1].Trim() );
  261. logwriter.WriteLine(tokens[2] + "rn");
  262. }
  263. }
  264. if (tokens[0] == "JOIN")
  265. {
  266. rtbChatIn.AppendText(tokens[1].Trim() );
  267. rtbChatIn.AppendText(" has joined the Chatrn");
  268. if(logging){
  269. logwriter.WriteLine(tokens[1]+" has joined the Chat");
  270. }
  271. string newguy = tokens[1].Trim(new char[]{'r','n'});
  272. lbChatters.Items.Add(newguy);
  273. }
  274. if (tokens[0] == "GONE")
  275. {
  276. rtbChatIn.AppendText(tokens[1].Trim() );
  277. rtbChatIn.AppendText(" has left the Chatrn");
  278. if(logging){
  279. logwriter.WriteLine(tokens[1]+" has left the Chat");
  280. }
  281. lbChatters.Items.Remove(tokens[1].Trim(new char[]{'r','n'}));
  282. }
  283. if (tokens[0] == "QUIT")
  284. {
  285. ns.Close();
  286. clientsocket.Close();
  287. keepalive = false;
  288. statusBar1.Text = "Server has stopped";
  289. connected= false;
  290. btnSend.Enabled = false;
  291. btnDisconnect.Enabled = false;
  292. }
  293. }
  294. catch(Exception e){}
  295. }
  296. }
  297. private void QuitChat() 
  298. {
  299. if(connected) {
  300. try{
  301. string command = "GONE|" + clientname;
  302. Byte[] outbytes = System.Text.Encoding.ASCII.GetBytes(command.ToCharArray());
  303. ns.Write(outbytes,0,outbytes.Length);
  304. clientsocket.Close();
  305. }
  306. catch(Exception ex){
  307. }
  308. }
  309. if(logging)
  310. logwriter.Close();
  311. if(receive != null && receive.IsAlive)
  312. receive.Abort();
  313. this.Text = "ChatClient";
  314. }
  315. private void StartStopLogging() 
  316. {
  317. if(!logging){
  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 = "Stop Logging";
  325. statusBar1.Text = "Connected - Log on";
  326. }
  327. else{
  328. logwriter.Close();
  329. logging = false;
  330. btnLog.Text = "Start Logging";
  331. statusBar1.Text = "Connected - Log off";
  332. }
  333. }
  334. /// <summary>
  335. /// The main entry point for the application.
  336. /// </summary>
  337. [STAThread]
  338. static void Main(String[] args) 
  339. {
  340. ChatClientForm cf = new ChatClientForm();
  341. if(args.Length == 0)
  342. cf.serveraddress = "localhost";
  343. else
  344. cf.serveraddress = args[0];
  345. Application.Run(cf);
  346. }
  347. private void btnConnect_Click(object sender, System.EventArgs e)
  348. {
  349. if(ChatOut.Text == ""){
  350. MessageBox.Show("Enter a name in the box before connecting","Error",
  351. MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
  352. return;
  353. }
  354. else
  355. clientname = ChatOut.Text;
  356. EstablishConnection();
  357. if(connected)
  358. {
  359. RegisterWithServer();
  360. receive = new Thread(new ThreadStart(ReceiveChat));
  361. receive.Start();
  362. btnSend.Enabled = true;
  363. btnConnect.Enabled = false;
  364. ChatOut.Text = "";
  365. }
  366. }
  367. private void btnSend_Click(object sender, System.EventArgs e)
  368. {
  369. try{
  370. string dclient = "";
  371. if(!privatemode){
  372. string pubcommand = "CHAT|" + clientname +": "+ChatOut.Text + "rn";
  373. Byte[] outbytes = System.Text.Encoding.ASCII.GetBytes(pubcommand.ToCharArray());
  374. ns.Write(outbytes,0,outbytes.Length);
  375. ChatOut.Text = "";
  376. }
  377. else{
  378. if(lbChatters.SelectedIndex == -1){
  379. MessageBox.Show("Select a chatter name from the list","Error",
  380. MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
  381. return;
  382. }
  383. string destclient = lbChatters.SelectedItem.ToString();
  384. string command = "PRIV|" + clientname + "|: " + ChatOut.Text + "|" + destclient;
  385. Byte[] outbytes = System.Text.Encoding.ASCII.GetBytes(command.ToCharArray());
  386. ns.Write(outbytes,0,outbytes.Length);
  387. ChatOut.Text = "";
  388. }
  389. }
  390. catch(Exception ex){
  391. MessageBox.Show("Connection with Server lost","Error",
  392. MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
  393. ns.Close();
  394. clientsocket.Close();
  395. if(receive != null && receive.IsAlive)
  396. receive.Abort();
  397. connected = false;
  398. statusBar1.Text = "Disconnected";
  399. }
  400. }
  401. private void btnDisconnect_Click(object sender, System.EventArgs e)
  402. {
  403. QuitChat();
  404. btnDisconnect.Enabled = false;
  405. btnConnect.Enabled = true;
  406. btnSend.Enabled = false;
  407. ns.Close();
  408. clientsocket.Close();
  409. receive.Abort();
  410. connected = false;
  411. lbChatters.Items.Clear();
  412. statusBar1.Text = "Disconnected";
  413. }
  414. private void ChatOut_KeyPress(object sender, System.Windows.Forms.KeyPressEventArgs e) {
  415. if(e.KeyChar == 'r')
  416. if(connected)
  417. btnSend_Click(sender, e);
  418. else
  419. btnConnect_Click(sender, e);
  420. }
  421. private void btnLog_Click(object sender, System.EventArgs e) {
  422. StartStopLogging();
  423. }
  424. private void cbPrivate_CheckedChanged(object sender, System.EventArgs e) {
  425. if(cbPrivate.Checked){
  426. privatemode = true;
  427. lbChatters.SelectionMode = System.Windows.Forms.SelectionMode.One;
  428. }
  429. else{
  430. privatemode = false;
  431. lbChatters.SelectionMode = System.Windows.Forms.SelectionMode.None;
  432. }
  433. }
  434. }
  435. }