版权说明:本文档由用户提供并上传,收益归属内容提供方,若内容存在侵权,请进行举报或认领
文档简介
1、郑州轻工业学院实训报告实训名称:网络聊天程序指导教师:姓名:学号:班级:提交日期:1. 实训目的通过开发一款网络聊天程序,熟练掌握多线程编程技术和tcp应 用编程技术。通过本实训,应达到如下目标:理解委托的概念,掌握线程之间通过委托与控件交互的方法。理解异常处理的机制,掌握异常处理语句的用法。理解线程的概念,掌握多线程编程的一般方法。掌握基于tcp的应用编程技术。2. 实训题目使用c#编程语言,开发一款网络聊天程序,玩家通过客户端登陆 远程的服务器,登陆成功后可以与其他在线的玩家通信,如下图所示。3. 功能描述1. 管理员可以启动停止服务器,服务器可以显示当前的在 线人数。2. 玩家可以登陆服
2、务器;登录后的玩家可以与其它在线的 玩家聊天;在线玩家关闭客户端即退岀登录。3. 用户可以注册账号登陆服务器,注册即可实现永久登陆。4. 需求分析根据功能描述可知,网络聊天程序的系统结构图如下所示。5.设计说明服务器界面如下:serverstart当前在线用户数:0客户端的登陆界面如下:陆m皿用户名:iclassic密码:飞卜;4验客户端的注册界面如下:客户端的聊天窗口如下:*6.源代码6.1服务器端user 类在server_54i3o7iioii4项目屮添加user类。user类的代码如下:using system;using system.collections.generic;usin
3、g system.linq;using system.text;using system.threading.tasks;using system.net.sockets;using systemo;namespace server_54i3o7iioii4 public class userpublic string username; publictcpciient die nt; public binaryreader breader;public binarywriter bwriter;public user(tcpclient client)this.client = die nt
4、;networkstream ns = dientgetstream(); breader = new binaryreader(ns); bwriter = new binarywriter(ns);public void close()breader.close();bwriter.close();client.close(); public void send(string message)bwriter. write(message); bwriter.flush();catch (exception ex)throw ex;public string receiveqtryretur
5、n breader.readstring();catch (exception)throw;userlist 类在项目中添加userlist类。userlist类的代码如下: using system;using system.collections.generic;using system.linq;using system.text;using system.threading.tasks;namespace server_54i3o7iioii4public class userlistpublic list<user> list;public userlist()list=
6、new list<user>();public void adduser(user user)list.add(user);public void removellser(user user)user.close();list.remove(user); public void removeaiiuser()for (int i = list.count-i; i >= o; i-)removeuser(listi);public void sendtoaiiuser(user user, string str)/给所有人发消息 string split = str.spli
7、tc;);/把接收的字符串分离if (splito="login")/判断是否为新登陆foreach (user u in list)/如果为新登陆,从用户集合获取每一个登 陆用户u.send(str);/给每个用户发送新用户登陆的消息u.se nd(”logi rv+u.username);if (u.username!=spliti)user.sendc'login," + u.username);不会给自己发送elseforeach (user u in list)/如果不是新用户登陆信息,则给除自己外 每个用户发送消息if (u.username!
8、=spliti)u.se nd(str);public void getaiiname(user user)foreach (user u in list)if (user = u)contin ue;user.send("getaiinamez" + u.username);mainwindow 代码:using system;using system.collections.generic;using system.linq;using system.text;using system.threading.tasks;using system .windows;usin
9、g system .windows. controls;using system.windows.data;using system.windows.documents;using system.windowsnput;using system .windows. media;using system .windows. media .imaging;using system.windows.navigation;using system .windows. shapes;using system.net.sockets;using system .net;using systemo;name
10、space server_54i3o7iioii4/<summary>iii mainwindow.xaml 的交互逻辑iii </summary>public partial class mainwindow : windowpublic tcpliste ner listener;public userlist userlist;public int port;public bool isexit;public int onlineuser;public mainwindow()in itializecomp onen t();port = 1005;listene
11、r = new t卬listener(ipaddress.anyport);/绑定ip端口号用于侦 听userlist = new userlist();isexit = true;onlineuser = 0;btnstopsenabled = false;private void btnstart_click(object sender, routedeventargse)listener.startq;/ 开始侦听 isexit = false;task.run() => connectlisten();/启动侦听连接线程 btnstartsen abled = false; bt
12、nstopsenabled = true;public void connectlisten()/用于侦听来自客户端的连接请求while (sisexit)tcpciient die nt;tryclient = listener.accepttcpclient();/接受连接请求,连接成功catch (exception)brea k;如有异常跳出侦听user newuser = new user(client); userlist.addllser( newuser);task.run() => receive(newuser);public void receive(user us
13、er)string message = null;while (!isexit)message = user.receive(); catch (exception)string split = message.split('z'); switch (splito)case "login":string readtext = readuserlnfo();bool isleagle = true; foreach (string userlnfotext in readtext)string str = userlnfotext.splitf,');
14、/用逗号分隔获取到的每行用户数据if (spliti=stro&&split2=stri)/将用户输入与此行的用户名密码对比,为真则登陆成功 foreach (user u in userlistist)讦(u.username=spliti)/检测该用户是否己经登陆isleagle = false; break;if(isleagle)/如果没登陆,添加进用户列表user.username = spliti;userlist.sendtoaiiuser(user, message); onlineuser+; onlineshow.dispatchern voke()=>
15、;onlineshow.text ="当前在线用户数:” + onlineuser);如果没有,发送sorrybreak;else/如果己登陆,发送sorryuser.se nd("sorry"); userlist.removellser(user);if (isleagle = false)/判断用户信息文本中是否有该用户,user.se nd(”sorry“);userlist.removeuser(user);break;case "register":bool issame = false;string readusername =
16、readllserlnfo(); foreach (string userlnfotext in readusername)/循环查找 用户信息是否有重名string str = userlnfotext.splitc/);if (stro=spliti)user.se ndc'egsorry'1);issame = true; break;/如果有重名,跳出循环elsecon tinue;讦(!issame)/循环结朿没有重名可以添加进去var a = appdomai n.currentdomain;file.appe ndalltext(a. basedirectory+
17、©"userlnfo.txt", spliti + split2 + encoding.default);user.se nd(jsregistel);break;case "talk":string receiver = split2; foreach (user u in userlist.list)if (u.username=receiver)u.se nd(message);user.send(message);break;case "logout": userlist.sendtoaiiuser(user, me
18、ssage); userlist.removellser(user); onlin euser-;onlineshow.dispatchernvoke() => onlineshow.text = n 当前在线用户数:"+onlinellser);break;case "getaiiname":userlist.getallname(user); break;default:break;private string readuserlnfo()var a = appdomain.currentdomain;/ 获取当前应用程序域string pathuser
19、lnfo = a.basedirectory + "userlnfo.txt";/确定用户信 息的文本位置string readtext = file.readalilinescpathuserlnfo, encoding.default);/ 逐行读取文本存入数组return readtext;private void btnstop_click(object sender, routedeventargse)userlist.removeaiiuser();onlineshow.dispatcher.invoke() => onlineshow.text =&qu
20、ot;当前在线用户 数:ou);isexit = true;listener.stopo;btnstartsen abled = true;btnstopsenabled = false;privatevoidwindow_closi ng_i(objectsen der,system.componentmodel.canceleve ntargs e)userlist.removealluser();isexit = true;listener.stopo;6.2客户端user 类using system;using system.collections.generic;using syst
21、em.linq;using system.text;using system.threading.tasks;using systemnet.sockets;using systemo; n amespace client_54i3o7iioii4public class userpublic string username; publictcpciie nt die nt; public binaryreader breader; public binarywriter bwrite;public user(tcpclie nt die nt)this.die nt = die nt;net
22、workstream ns = dientgetstream(); breader = new binaryreader(ns); bwrite = new binarywriter(ns);public void close()if (breader!=null)breader.close();讦(bwrite!=null)bwrite.close();讦(client!=null)client.close();public void send(string message)trybwrite.write(message); bwrite.flush();catch (exception e
23、x)throw ex;public string receive()tryreturn breader.readstring();catch (exception)throw;login代码using system;using system.collections.generic;using system.linq;using system.text;using system.threading.tasks;using system.windows;using system.windows.controls;using system.windows.data;using system.wind
24、ows.documents; using system.windowsnput;using system.windows.media;using system.windows. media imaging;using system.windows.shapes;using system .net. sockets;using system.threading; namespace client_54i3o7iioii4iii <summary>iii login.xaml的交互逻辑iii </summary>public partial class login : wi
25、ndowpublic user user; public int port; public bool isconnect; publictcpciie nt die nt;public login()in itializecompone nt(); client = n ewtcpciie nt(); port = 1005; jsconnect = false;private void btnregister_click(object sender, routedeventargs e) tryif (isc onn ect= false)trydient.connect("i72
26、.20.82.9,,/ port);user = new user(clie nt);isco nn ect = true;catch (exception)messagebox.show(”连接服务器失败! ”);register reg = new register(user);reg.show();catch (exception ex)messagebox.show("连接失败! ”+ex);private void btnlogin_click(object sender, routedeventargs e)ii使用一个intptr类型值来存储加密字符串的起始点intpt
27、rp=system.r un timen teropservices. marshal.securestri ngtobstr(this.tbuserpassword.secur epassword);ii使ffl.net内部算法把intptr指向处的字符集合转换成字符串stringpassword=system.r un timen teropservices. marshal. ptrtostringbstr(p);if (tbusername.text = "" | password ="")messagebox.show("iw输入用户
28、名和密码! ”);return;tryif (isc onn ect=false)client.corrnect("i"/ port);user = new user(clie nt); isc orrn ect = true;catch (exception)messagebox.show("连接服务器失败! ”);task.run() => receiveo);user.username = tbusername.text;sen dmessage("login/' + user.username + passwor
29、d);catch (exception)messagebox.show("连接失败! ”);private void sendmessage(string message)tryuser.se nd(message);catch(exception ex)isco nn ect = false;messagebox.show("发送失败! ”+ex);sen der,privatevoidwindow_closi ng_i(objectsystem.compone ntmodel.canceleventargs e)if (isc onn ect)isco nn ect =
30、 false;sendmessage("logoutz" + user.username);if (user!=null)user.close();public void receive()string message;while (isconnect)trymessage = user.receive();catchiscorrn ect = false;string 口 sp-it h messagesp=5-)jswitch (sp=to)case=ogin.=if (sp-itenn user.username)/舍加啟二口也j 池皿cu3障爭莊& this
31、bispatcher.-nvokeohv isconneftn fa-sejmessagebox.show(ksffig7一 =)jmainwindow mw h newmainwindow(user;loginpage)jmwshow()j (hishdeoj 一)j一breakjcase 二 sory.=messageboxshow(=5t®£tzbe ;)iscormect h fa-sejbre*defau-仃break"rivate void windowlloadedll(objecr sender; routedeventargs e)try宀c=e
32、ntconneft(hr722o825poajuser h new user(c=ent)j isconnect h quej一ca(ch (exception)messagebox.showc'韶冷富 一 =)jprivate void close_click(object sender, routedeventargs e) this.close();private void window_mousedow n_ i(object sen der, mousebutt on eve ntargs e) if (e.leftbutto n = mousebuttonstate. pr
33、essed)dragmove();private void loginpage_keydown(object sender, keyeventargs e) if (e. key=key. enter)btnlogin_click(sender; e);register 代码using system;using system.collections.generic;using system丄inq;using system.text;using system.threading.tasks;using system.windows;using system.windows.controls;u
34、sing system.windows.data;using system.windows.documents;using system.windowsnput;using system.windows.media;using system.windows.mediamaging;using system.windows.shapes;using systemnet.sockets;n amespace clien t_54i3o7iioii4iii <summary>ill register.xaml 的交互逻辑iii </summary> public partia
35、l class register: window public user user;public bool isconnect;public register(user user)in itializecomp onen t(); this.user = user; private void btn reginter_click(object sender, routed eventargs e)ii使用一个intptr类型值来存储加密字符串的起始点intptrp=system. r un timeteropservices.marshal.securestri ngtobstr(this.t
36、breuserpasswordsec urepassword);ii使用.net内部算法把intptr指向处的字符集合转换成字符串stringpasswordi=system.ru ntimen teropservices. marshal.ptrtostri ngbstr(p);p=system.runtimeteropservices.marshal.securestringtobstr(this.tbreuserpasswordok. securepassword);stringpassword2=system.ru ntime .in teropservices.marshal.ptr
37、tostri ngbstr(p);if (tbreusername.text = "" | passwordi = "" | password2 ="")messagebox.show("iw输入用户名和密码! “);return;else if (passwordi!=password2)messagebox.show("两次密码不匹配! “);return;isco nn ect = true;task.run() => receiveo);sen dmessagec'register,"
38、; + tbreusername.text + passwordi); catch (exception ex)isco nn ect = false; messagebox.show("连接失败! "+ex);public void sendmessage(string message) user.se nd(message);catch (exception ex)messagebox.show("发送失败"+ex);public void receive()string message; while (isconnect) message = us
39、er.receive();catchisc on nect = false; break; string split = message.splitc,');switch (splito)case "regsorry11:messagebox.show("b存在该用户! ”); isco nn ect = false;break;case "isregister":messagebox.show("fe喜!注册成功!");isco nn ect = false;this.close(); break;private void
40、close_click(object sender, routedeventargs e) this.close();private void window_mousedow(object sender, mousebuttoneventargs e) 讦(e.leftbutton 二二 mousebuttonstate.pressed)dragmove();mainwindow 代码using system;using system.collections.generic;using system.linq;using system.text;using system.threading.t
41、asks;using system.windows;using system.windows.controls;using system.windows.data;using system.windows.documents;using system.windowsnput;using system.windows.media;using system.windows. media .imaging;using system.windows.navigation;using system.windows.shapes;using system.runtimenteropservices;usi
42、ng system .net. sockets;using system.media; n amespace clien t_54i3o7iioii4ill <summary>iii mainwindow.xaml 的交互逻辑iii </summary>public partial class mainwindow : windowpublic user user;publictcpciient die nt;public bool isconnect;public login loginpage;public mainwindow(user userzlogin lo
43、ginpage)lnitializecomponent();this.user = user; isco rin ect = true; this.title = user.username + "的聊天室“; tbtitle.text =" 欢迎您,” + user.username; this.loginpage = loginpage; task.run() => receiveo);private void btnsendmessage_click(object sender, routedeventargse)讦(sendmessagebox.text=,h
44、,)addtalkmessage("ir输入发送的消息! ”); return;if (usershowbox.selectedl ndex=-i)for (int i = o; i < usershowboxtems.count; i+)addtalkmessage("请选择用户! “);return;string chooseuser = usershowbox.selectedltem.tostring();sen dmessagec'talk,11 + user.username + chooseuser +"/"+datetime
45、.now.tostring("hh:mm:ss")+"/" +sendmessagebox.text);sen dmessagebox.clear();public void receive()string message; while (isconnect) message = user.receive();catch (exception)btnsen dmessage.dispatcher.! nvoke()=> btnse ndmessagesen abled = false );messagebox.showc噺开连接!");d
46、eluseronline(user.username, true);isc on nect = false;break;string split = message.split(7);switch (splito)case “login”:if (spliti!=user.username)adduseronline(spliti);break;case "talk'*:string s =,h;的问题for (int i = 4; i < split.length -1; i+)/可以解决收到英文逗号s += spliti + '7's += spli
47、tsplit.length -1;if (spliti=user.username)addtalkmessage(h我对 11 + split2 + 11 说(n + splitelseaddtalkmessage(spliti + "对我说("+ splitfe + “):、”' +s);sou ndplayer si = new soundplayer("msg.wav"); si.playo;break;case "logout":deluseronlinecsplitti, false);break;case &quo
48、t;getaiiname":adduseronline(spliti);break;default:break; public void deluseronline(string namezbool all) usershowbox.dispatcher. i nvoke()=>if (all)usershowboxtems.clear。;elseusershowboxtems. remove (n ame););public void adduseronline(string str)/向在线用户列表添加用户usershowbox.dispatcher.lnvoke() =&
49、gt; usershowbox.items.add(str); sv2.dispatcher.! nv oke()=>sv2.scrolltoe nd();public void sendmessage(string message)tryuser.send(message);catch (exception) addtalkmessage("发送失败");public void addtalkmessage(string message)/向聊天框添加消息 messageshowbox. dispatchernvoke()=> messageshowbox.t
50、ext += message + w );svi.dispatchern voke()=> svi.scrolltoendosen der,);privatevoidwindow_closi ng_i(objectsystem.componentmodel.canceleventargs e)if (isc on nect)iscon nect 二 false;sen dmessage(l,logout/h + user.username);if (user!=null)logi npage.close(); user.close();private void window_loaded
51、_i(object sender, routedeventargs e)user.send(l,getaiiname,');private void window_keydown_i(object sender, keyeventargs e)if (e.key=key.enter&&sendmethod.lschecked=false)btnsendmessage_click(sender; e);if (keyboard.modifiers=modifierkeys.control&&e.key = key.enter && sen
52、dmethodschecked = true)btnsendmessage_click(sender; e);private void close_click(object sender, routedeventargs e)this.close();private void window_mousedown_i(object sender, mousebuttoneventargs e)/可以鼠标拖动if (e.leftbutton 二二 mousebuttonstate.pressed)dragmove();i7. 测试报告测试用例玩家登陆1) 测试客户端是否能在服务器启动时登陆。2) 测试客户端是否能在服务器时停止时登陆。3) 测试客户端是
温馨提示
- 1. 本站所有资源如无特殊说明,都需要本地电脑安装OFFICE2007和PDF阅读器。图纸软件为CAD,CAXA,PROE,UG,SolidWorks等.压缩文件请下载最新的WinRAR软件解压。
- 2. 本站的文档不包含任何第三方提供的附件图纸等,如果需要附件,请联系上传者。文件的所有权益归上传用户所有。
- 3. 本站RAR压缩包中若带图纸,网页内容里面会有图纸预览,若没有图纸预览就没有图纸。
- 4. 未经权益所有人同意不得将文件中的内容挪作商业或盈利用途。
- 5. 人人文库网仅提供信息存储空间,仅对用户上传内容的表现方式做保护处理,对用户上传分享的文档内容本身不做任何修改或编辑,并不能对任何下载内容负责。
- 6. 下载文件中如有侵权或不适当内容,请与我们联系,我们立即纠正。
- 7. 本站不保证下载资源的准确性、安全性和完整性, 同时也不承担用户因使用这些下载资源对自己和他人造成任何形式的伤害或损失。
最新文档
- 建筑学咨询行业市场调研分析报告
- 充电桩智能管理行业营销策略方案
- 公司治理法律服务行业经营分析报告
- 印刷机用盘纸产业链招商引资的调研报告
- 女式披肩产品供应链分析
- 安排举办和组织专家讨论会行业相关项目经营管理报告
- 室内用空气芳香剂产业链招商引资的调研报告
- 木片切削机产品供应链分析
- 宽顶无沿圆帽产业链招商引资的调研报告
- 工业用封口机产品供应链分析
- 2024年区卫生健康系统公开招聘大学生村医考试题及答案
- 廉洁纪律十道题
- 高三英语 时政类语篇型填空专项训练
- 八年级生物上册 5.14.3《神奇的微生物》说课稿 (新版)苏教版
- 2024年度信息化教学校本研修实施方案
- 2024-2030年中国装备故障预测和健康管理(PHM)行业发展现状与前景预测分析研究报告
- 2024年中移建设限公司安徽分公司社会招聘12人高频难、易错点500题模拟试题附带答案详解
- 2024秋期国家开放大学《政治学原理》一平台在线形考(形考任务二)试题及答案
- 2024年浙江省宁波市初二上学期期中历史试题及解答参考
- 关爱流浪小动物(教学设计)-2024-2025学年三年级上册综合实践活动教科版
- 历史知识清单2024~2025学年统编版九年级历史上册
评论
0/150
提交评论