




已阅读5页,还剩12页未读, 继续免费阅读
版权说明:本文档由用户提供并上传,收益归属内容提供方,若内容存在侵权,请进行举报或认领
文档简介
简单的多人聊天(C#)/*8ChatServer:*/using System;using System.Drawing;using System.Collections;using System.ComponentModel;using System.Windows.Forms;using System.Data;using System.Threading;using System.Net.Sockets;using System.Net;namespace Chat_Server/ / Form1 的摘要说明。/ public class Form1 : System.Windows.Forms.Form/ / 必需的设计器变量。/ private System.ComponentModel.Container components = null;static int listenport=6666;Socket clientsocket;private System.Windows.Forms.ListBox lbClients;ArrayList clients;private System.Windows.Forms.Button button1;Thread clientservice;private System.Windows.Forms.Label label1;Thread threadListen;public Form1()InitializeComponent();/ / 清理所有正在使用的资源。/ protected override void Dispose( bool disposing )if( disposing )if(clientservice != null)clientservice.Abort();if(threadListen != null)trythreadListen.Abort();catch(Exception ex)threadListen = null;if (components != null) components.Dispose();base.Dispose( disposing );#region Windows 窗体设计器生成的代码/ / 设计器支持所需的方法 - 不要使用代码编辑器修改/ 此方法的内容。/ private void InitializeComponent()this.lbClients = new System.Windows.Forms.ListBox();this.button1 = new System.Windows.Forms.Button();this.label1 = new System.Windows.Forms.Label();this.SuspendLayout();/ / lbClients/ this.lbClients.ItemHeight = 12;this.lbClients.Location = new System.Drawing.Point(16, 24);this.lbClients.Name = lbClients;this.lbClients.Size = new System.Drawing.Size(184, 268);this.lbClients.TabIndex = 0;/ / button1/ this.button1.Location = new System.Drawing.Point(272, 56);this.button1.Name = button1;this.button1.TabIndex = 1;this.button1.Text = button1;this.button1.Click += new System.EventHandler(this.button1_Click);/ / label1/ this.label1.Location = new System.Drawing.Point(240, 136);this.label1.Name = label1;this.label1.Size = new System.Drawing.Size(120, 32);this.label1.TabIndex = 2;this.label1.Text = label1;/ / Form1/ this.AutoScaleBaseSize = new System.Drawing.Size(6, 14);this.ClientSize = new System.Drawing.Size(368, 309);this.Controls.Add(this.label1);this.Controls.Add(this.button1);this.Controls.Add(this.lbClients);this.Name = Form1;this.Text = Form1;this.Load += new System.EventHandler(this.Form1_Load);this.ResumeLayout(false);#endregion/ / 应用程序的主入口点。/ STAThreadstatic void Main() Application.Run(new Form1();private void StartListening() TcpListener listener = new TcpListener(listenport);listener.Start();label1.Text = listening.;while (true) trySocket s = listener.AcceptSocket(); clientsocket = s; clientservice = new Thread(new ThreadStart(ServiceClient); clientservice.Start(); catch(Exception ex)MessageBox.Show(listening Error: +ex.Message);private void ServiceClient() Socket client = clientsocket; bool keepalive = true; while (keepalive) Byte buffer = new Byte1024; int bufLen = 0;trybufLen = client.Available ;client.Receive(buffer,0,bufLen,SocketFlags.None); if(bufLen=0)continue;catch(Exception ex)MessageBox.Show(Receive Error:+ex.Message);return;string clientcommand = System.Text.Encoding.ASCII.GetString(buffer).Substring(0,bufLen); string tokens = clientcommand.Split(new Char|); Console.WriteLine(clientcommand); if (tokens0 = CONN) for(int n=0; nclients.Count;n+) Client cl = (Client)clientsn; SendToClient(cl, JOIN| + tokens1); EndPoint ep = client.RemoteEndPoint; Client c = new Client(tokens1, ep, clientservice, client); string message = LIST| + GetChatterList() +rn; SendToClient(c, message); clients.Add(c); lbClients.Items.Add(c); if (tokens0 = CHAT) for(int n=0; nclients.Count;n+) Client cl = (Client)clientsn; SendToClient(cl, clientcommand); if (tokens0 = PRIV) string destclient = tokens3; for(int n=0; nclients.Count;n+) Client cl = (Client)clientsn; if(cl.Name.CompareTo(tokens3) = 0) SendToClient(cl, clientcommand); if(cl.Name.CompareTo(tokens1) = 0) SendToClient(cl, clientcommand); if (tokens0 = GONE) int remove = 0; bool found = false; int c = clients.Count; for(int n=0; nclients.Count;n+) Client cl = (Client)clientsn; SendToClient(cl, clientcommand); if(cl.Name.CompareTo(tokens1) = 0) remove = n; found = true; lbClients.Items.Remove(cl); if(found) clients.RemoveAt(remove); client.Close(); keepalive = false; private string GetChatterList()string result = ;for(int i=0;iclients.Count;i+)result += (Client)clientsi).Name+|;return result;private void SendToClient(Client cl,string clientCommand)Byte message = System.Text.Encoding.ASCII.GetBytes(clientCommand);Socket s = cl.Sock;if(s.Connected)s.Send(message,message.Length,0);private void Form1_Load(object sender, System.EventArgs e)clients = new ArrayList();private void button1_Click(object sender, System.EventArgs e)threadListen = new Thread(new ThreadStart(StartListening);threadListen.Start(); /* client类 */* 放于 chatServer 项目中 */using System; using System.Threading; namespace Chat_Server using System.Net.Sockets; using System.Net; / / Client 的摘要说明。 / public class Client private Thread clthread; private EndPoint endpoint; private string name; private Socket sock; public Client(string _name, EndPoint _endpoint, Thread _thread, Socket _sock) / TODO: 在此处添加构造函数逻辑 clthread = _thread; endpoint = _endpoint; name = _name; sock = _sock; public override string ToString() return endpoint.ToString()+ : + name; public Thread CLThread getreturn clthread; setclthread = value; public EndPoint Host getreturn endpoint; setendpoint = value; public string Name getreturn name; setname = value; public Socket Sock getreturn sock; setsock = value; /* chatClient */using System;using System.Drawing;using System.Collections;using System.ComponentModel;using System.Windows.Forms;using System.Data;using System.IO;using System.Net;using System.Net.Sockets;using System.Threading;namespace Chat_Client/ / Form1 的摘要说明。/ public class Form1 : System.Windows.Forms.Formprivate System.Windows.Forms.CheckBox checkBox1;private System.Windows.Forms.StatusBar statusBar1;NetworkStream ns;StreamReader sr;TcpClient clientsocket;bool connected;Thread receive;string serveraddress = 5;int serverport = 6666;private System.Windows.Forms.RichTextBox rtbChatIn;private System.Windows.Forms.ListBox lbChatters;private System.Windows.Forms.TextBox ChatOut;private System.Windows.Forms.Button btnDisconnect;private System.Windows.Forms.Button btnSend;private System.Windows.Forms.TextBox clientName;string clientname;private System.Windows.Forms.Button btnConnect;private System.ComponentModel.Container components = null;public Form1()InitializeComponent();/ / 清理所有正在使用的资源。/ protected override void Dispose( bool disposing )if( disposing )if(receive != null)QuitChat();if (components != null) components.Dispose();base.Dispose( disposing );#region Windows 窗体设计器生成的代码/ / 设计器支持所需的方法 - 不要使用代码编辑器修改/ 此方法的内容。/ private void InitializeComponent()this.lbChatters = new System.Windows.Forms.ListBox();this.rtbChatIn = new System.Windows.Forms.RichTextBox();this.checkBox1 = new System.Windows.Forms.CheckBox();this.ChatOut = new System.Windows.Forms.TextBox();this.btnSend = new System.Windows.Forms.Button();this.statusBar1 = new System.Windows.Forms.StatusBar();this.btnDisconnect = new System.Windows.Forms.Button();this.clientName = new System.Windows.Forms.TextBox();this.btnConnect = new System.Windows.Forms.Button();this.SuspendLayout();/ / lbChatters/ this.lbChatters.ItemHeight = 12;this.lbChatters.Location = new System.Drawing.Point(32, 40);this.lbChatters.Name = lbChatters;this.lbChatters.Size = new System.Drawing.Size(112, 172);this.lbChatters.TabIndex = 0;/ / rtbChatIn/ this.rtbChatIn.Location = new System.Drawing.Point(160, 40);this.rtbChatIn.Name = rtbChatIn;this.rtbChatIn.Size = new System.Drawing.Size(208, 176);this.rtbChatIn.TabIndex = 2;this.rtbChatIn.Text = ;/ / checkBox1/ this.checkBox1.Location = new System.Drawing.Point(16, 248);this.checkBox1.Name = checkBox1;this.checkBox1.TabIndex = 3;this.checkBox1.Text = checkBox1;/ / ChatOut/ this.ChatOut.Location = new System.Drawing.Point(136, 248);this.ChatOut.Name = ChatOut;this.ChatOut.Size = new System.Drawing.Size(136, 21);this.ChatOut.TabIndex = 4;this.ChatOut.Text = message;/ / btnSend/ this.btnSend.Location = new System.Drawing.Point(336, 248);this.btnSend.Name = btnSend;this.btnSend.TabIndex = 5;this.btnSend.Text = send;this.btnSend.Click += new System.EventHandler(this.btnSend_Click);/ / statusBar1/ this.statusBar1.Location = new System.Drawing.Point(0, 287);this.statusBar1.Name = statusBar1;this.statusBar1.Size = new System.Drawing.Size(464, 22);this.statusBar1.TabIndex = 6;this.statusBar1.Text = statusBar1;/ / btnDisconnect/ this.btnDisconnect.Enabled = false;this.btnDisconnect.Location = new System.Drawing.Point(392, 112);this.btnDisconnect.Name = btnDisconnect;this.btnDisconnect.Size = new System.Drawing.Size(64, 32);this.btnDisconnect.TabIndex = 7;this.btnDisconnect.Text = 断开;this.btnDisconnect.Click += new System.EventHandler(this.btnDisconnect_Click);/ / clientName/ this.clientName.Location = new System.Drawing.Point(96, 8);this.clientName.Name = clientName;this.clientName.TabIndex = 8;this.clientName.Text = name;/ / btnConnect/ this.btnConnect.Location = new System.Drawing.Point(392, 56);this.btnConnect.Name = btnConnect;this.btnConnect.Size = new System.Drawing.Size(64, 32);this.btnConnect.TabIndex = 9;this.btnConnect.Text = 连接;this.btnConnect.Click += new System.EventHandler(this.btnConnect_Click);/ / Form1/ this.AutoScaleBaseSize = new System.Drawing.Size(6, 14);this.ClientSize = new System.Drawing.Size(464, 309);this.Controls.Add(this.btnConnect);this.Controls.Add(this.clientName);this.Controls.Add(this.btnDisconnect);this.Controls.Add(this.statusBar1);this.Controls.Add(this.btnSend);this.Controls.Add(this.ChatOut);this.Controls.Add(this.checkBox1);this.Controls.Add(this.rtbChatIn);this.Controls.Add(this.lbChatters);this.Name = Form1;this.Text = Form1;this.ResumeLayout(false);#endregion/ / 应用程序的主入口点。/ STAThreadstatic void Main() Application.Run(new Form1();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() lbChatters.Items.Clear();clientname = clientName.Text;try string command = CONN| + clientname; /+rn; 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(|); if(tokens0 = LIST) statusBar1.Text = 已连接; btnDisconnect.Enabled = true; if(tokens1 != )for(int n=1; ntokens.Length;n+)lbChatters.Items.Add(tokensn.Trim(new charr,n); this.Text = clientname + :已连接到服务器; catch (Exception ex) MessageBox.Show(注册时发生错误!+ex.Message,错误, MessageBoxButtons.OK, MessageBoxIcon.Exclamation); connected = false; private void ReceiveChat() bool keepalive = true; while (keepalive) try Byte buffer = new Byte1024; / 2048?ns.Read(buffer,0,buffer.Length); string chatter = System.Text.Encoding.ASCII.GetString(buffer); string tokens = chatter.Split(new Char|); if (tokens0 = CHAT) rtbChatIn.AppendText(tokens1); /if(logging) /logwriter.WriteLine(tokens1); if (tokens0 = PRIV) rtbChatIn.AppendText(Private from ); rtbChatIn.AppendText(tokens1.Trim() ); rtbChatIn.AppendText(tokens2 + rn); /if(logging) / /logwriter.Write(Private from ); /logwriter.Write(tokens1.Trim() ); /logwriter.WriteLine(tokens2 + rn); / if (tokens0 = JOIN) rtbChatIn.AppendText(tokens1.Trim() ); rtbChatIn.AppendText( has joined the Chatrn); /if(logging) / /logwriter.WriteLine(tokens1+ has joined the Chat); / string newguy = tokens1.Trim(new charr,n); lbChatters.Items.Add(newguy); if (tokens0 = GONE) rtbChatIn.AppendText(tokens1.Trim() ); rtbChatIn.AppendTe
温馨提示
- 1. 本站所有资源如无特殊说明,都需要本地电脑安装OFFICE2007和PDF阅读器。图纸软件为CAD,CAXA,PROE,UG,SolidWorks等.压缩文件请下载最新的WinRAR软件解压。
- 2. 本站的文档不包含任何第三方提供的附件图纸等,如果需要附件,请联系上传者。文件的所有权益归上传用户所有。
- 3. 本站RAR压缩包中若带图纸,网页内容里面会有图纸预览,若没有图纸预览就没有图纸。
- 4. 未经权益所有人同意不得将文件中的内容挪作商业或盈利用途。
- 5. 人人文库网仅提供信息存储空间,仅对用户上传内容的表现方式做保护处理,对用户上传分享的文档内容本身不做任何修改或编辑,并不能对任何下载内容负责。
- 6. 下载文件中如有侵权或不适当内容,请与我们联系,我们立即纠正。
- 7. 本站不保证下载资源的准确性、安全性和完整性, 同时也不承担用户因使用这些下载资源对自己和他人造成任何形式的伤害或损失。
最新文档
- 人教部编版七年级下册一棵小桃树教学设计及反思
- 2024四川古蔺县山态农业发展有限公司招聘1人笔试参考题库附带答案详解
- 人美版八年级下册8.色彩风景画教案及反思
- 人教版三年级音乐下册(五线谱)第1单元《森林与小鸟》教学设计
- 2024北京首旅集团战略投资部副部长社会公开招聘1人笔试参考题库附带答案详解
- 高空拓展安全培训课件
- 初中政治 (道德与法治)人教版(2024)九年级上册第一单元 富强与创新第二课 创新驱动发展创新改变生活教学设计及反思
- 人教版八年级美术上册教学设计:第2课 色彩的感染力
- 2024云南鸿园电力物业服务有限公司招聘6人笔试参考题库附带答案详解
- 吊车安全教育培训
- 绘本故事:睡睡镇
- 酒店住宿水单模板1
- 【BIM技术在施工质量控制中的应用研究-以海棠花园项目为例18000字(论文)】
- 保利幕墙工程技术标述标课件
- 体育50米快速跑教案9篇
- 大跨结构的经典之作-鸟巢论文
- 订单延期交货的相关处理规定
- 有机溶剂作业场所个人职业病防护用品使用规范
- 汽车维修工(中级)技能理论考试核心题库(职校考试600题)
- 工商联各项规章制度
- 泸州老窖大学生入职培训试题三
评论
0/150
提交评论