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

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