版权说明:本文档由用户提供并上传,收益归属内容提供方,若内容存在侵权,请进行举报或认领
文档简介
1、 高级网络程序设计课程设计报告题 目 基于TCP的局域网即时消息系统的客户端和服务器端的设计与实现学 号 姓 名 计算机网络工程教研室2016年01月11 日目 录一、课程设计内容.2二、设计目的.2三、设计步骤.2四、具体要求. 3五、实验代码. 3六、实验结果. 20七、参考文献. 22八、实验心得. 22一、课程设计内容1 Winsock的启动与终止。2 Winsock的创建及绑定和关闭。3 建立通信连接listen及accept和connect。4 数据的传输。5 简单的客户机/服务器之间的通信。二、设计目的1 熟悉Windows Socket的常用函数的形式和使用方法,理解数据通信的
2、过程。2 掌握如何利用C#进行TCP协议开发,完成基于TCP的局域网即时消息系统的客户端和服务器端的设计与实现。三、设计步骤 在TCP/IP网络中两个进程间的相互作用的主机模式是客户机/服务器模式(Client/Server model)。该模式的建立基于以下两点:(1)非对等作用;(2)通信完全是异步的。客户机/服务器模式在操作过程中采取的是主动请示方式:1、首先服务器方要先启动,并根据请示提供相应服务,其过程如下:(1)打开一通信通道并告知本地主机,它愿意在某一个公认地址上接收客户请求。(2)等待客户请求到达该端口。(3)接收到重复服务请求,处理该请求并发送应答信号。(4)返回第二步,等待
3、另一客户请求(5)关闭服务器。2、客户方:(1)打开一通信通道,并连接到服务器所在主机的特定端口。(2)向服务器发送服务请求报文,等待并接收应答;继续提出请求(3)请求结束后关闭通信通道并终止。3、TCP连接的套接字的系统调用时序图如图2.1所示。4、TCP连接的应用程序流程图如图2.2所示。图2.1 TCP连接的套接字的系统调用时序图图2.2 TCP连接的应用程序流程图 四、具体要求需要有基本的双人、多人文字聊天功能,上下线通知,在线用户列表,点对点文件传输,所有的文字或文件传输需支持CRC-32校验,具有出错重传机制;五、实验代码(1)客户机:using System;using Syst
4、em.Collections.Generic;using System.ComponentModel;using System.Data;using System.Drawing;using System.IO;using System.Linq;using System.Net;using System.Net.Sockets;using System.Text;using System.Threading.Tasks;using System.Windows.Forms;namespace SocketClient public partial class Form1 : Form pub
5、lic Form1() InitializeComponent(); Socket _socketSend; private void btnStart_Click(object sender, EventArgs e) /创建负责通信的Socket: if (_socketSend = null | _socketSend.Connected = false) _socketSend = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); IPAddress ip = IPAddress.P
6、arse(txtServer.Text); IPEndPoint point = new IPEndPoint(ip, Convert.ToInt32(txtPoint.Text); SocketAsyncEventArgs socketE = new SocketAsyncEventArgs(); socketE.Completed += socketE_Completed; socketE.RemoteEndPoint = point; try _socketSend.ConnectAsync(socketE); catch (SocketException) else ShowMsg(&
7、quot;系统提示:", "已经连接到服务器:" + _socketSend.RemoteEndPoint.ToString() + "请重新连接!"); void socketE_Completed(object sender, SocketAsyncEventArgs e) Socket acceptSocket = e.ConnectSocket; if (acceptSocket = null) ShowMsg("系统提示:", "向" + e.RemoteEndPoint.ToString()
8、+ "的连接建立失败!"); return; string endPoint = acceptSocket.RemoteEndPoint.ToString(); ShowMsg("系统提示:", "向" + endPoint + "的连接成功建立!"); while (true) /客户端连接成功后,客户端应该接受服务器发来的消息 byte buffer = new byte1024 * 1024 * 2; /实际接受到的有效字节数 int r = 0; try r = acceptSocket.Receive(b
9、uffer); catch (SocketException) r = 0; if (r = 0) if (acceptSocket.Connected) ShowMsg("系统提示:", "向" + endPoint + "的连接断开!"); acceptSocket.Close(); break; /如果发送的数据是文字(标识 0 ) if (buffer0 = 0) string str = Encoding.UTF8.GetString(buffer, 1, r - 1); ShowMsg(endPoint + ":
10、", str); else if (buffer0 = 1) string fileName = Encoding.UTF8.GetString(buffer, 17, 1000).Trim('0'); SingleObject.GetSingle().LastSendedFile = Path.GetTempFileName(); using (FileStream fsWrite = new FileStream(SingleObject.GetSingle().LastSendedFile, FileMode.OpenOrCreate, FileAccess.W
11、rite) fsWrite.Write(buffer, 0, r); ShowMsg(endPoint + ":", "给你发送了文件:" + fileName); else if (buffer0 = 2) SingleObject.GetSingle().IsMove = true; else ShowMsg("系统消息:", "无法识别“" + endPoint + "”发送来的消息类型!"); private void Received() this.Activate(); privat
12、e void MoveForm() Received(); Random r = new Random(); Point location = this.Location; DateTime time = DateTime.Now; while (DateTime.Now - time) < TimeSpan.FromSeconds(1.5) Point nextPoint = new Point(location.X + r.Next(-10, 11), location.Y + r.Next(-10, 11); this.Location = nextPoint; System.Th
13、reading.Thread.Sleep(10); this.Location = location; private void btnSendMsg_Click(object sender, EventArgs e) if (_socketSend = null | _socketSend.Connected = false) ShowMsg("系统提示:", "请先连接服务器,再发送消息!"); return; string endPoint = _socketSend.RemoteEndPoint.ToString(); byte basicBuf
14、fer = Encoding.UTF8.GetBytes(txtMsg.Text); List<byte> list = new List<byte>(basicBuffer.Length + 1); list.Add(0); list.AddRange(basicBuffer); byte buffer = list.ToArray(); list = null; try _socketSend.Send(buffer); ShowMsg("向" + endPoint + "发送:", txtMsg.Text); catch (
15、SocketException) txtMsg.Clear(); private void ShowMsg(string sender, string msg) string time = DateTime.Now.ToString("hh:mm:ss"); SingleObject.GetSingle().LogString.AppendLine(time + " " + sender); SingleObject.GetSingle().LogString.AppendLine(msg); SingleObject.GetSingle().LogSt
16、ring.AppendLine(); private void timerChange_Tick(object sender, EventArgs e) lblTime.Text = DateTime.Now.ToString(); /txtLog的数据 if (!txtLogUserChange && !(txtLog.Text = SingleObject.GetSingle().LogString.ToString() txtLogAutoChange = true; txtLog.Text = SingleObject.GetSingle().LogString.ToS
17、tring(); txtLogAutoChange = false; /是否震动 if (SingleObject.GetSingle().IsMove) MoveForm(); SingleObject.GetSingle().IsMove = false; bool txtLogUserChange = false, txtLogAutoChange = false; private void txtLog_TextChanged(object sender, EventArgs e) if (txtLogAutoChange) return; txtLogUserChange = tru
18、e; private void btnClose_Click(object sender, EventArgs e) if (_socketSend != null | _socketSend.Connected = true) ShowMsg("系统提示:", "服务器已经断开或未连接!"); return; try ShowMsg("系统提示:", "向" + _socketSend.RemoteEndPoint.ToString() + "的连接断开!"); _socketSend.Clo
19、se(); catch (SocketException) private void btnMoveForm_Click(object sender, EventArgs e) if (_socketSend = null | _socketSend.Connected = false) ShowMsg("系统提示:", "请先连接服务器,再发送消息!"); return; string endPoint = _socketSend.RemoteEndPoint.ToString(); byte buffer = new byte1 2 ; try _s
20、ocketSend.Send(buffer); ShowMsg("向" + endPoint + "发送:", "你给对方发送了一个震动!"); catch (SocketException) MoveForm(); private void btnReceiveFile_Click(object sender, EventArgs e) if (string.IsNullOrEmpty(SingleObject.GetSingle().LastSendedFile) ShowMsg("系统提示:", "
21、目前没有接收到任何的文件!"); return; byte buffer = new byte1024 * 1024 * 5 + 1024; int r; using (FileStream fsRead = new FileStream(SingleObject.GetSingle().LastSendedFile, FileMode.OpenOrCreate, FileAccess.Read) r = fsRead.Read(buffer, 0, buffer.Length); byte guidb = new byte16; for (int i = 0; i < gui
22、db.Length; i+) guidbi = bufferi + 1; Guid guid = new Guid(guidb);/buffer, 1, 16); string fileName = Encoding.UTF8.GetString(buffer, 17, 1000).Trim('0'); SaveFileDialog sfd = new SaveFileDialog(); sfd.FileName = fileName; sfd.DefaultExt = Path.GetExtension(fileName); sfd.Filter = "所有文件|*
23、.*" sfd.Title = "请选择需要保存的路径" if (sfd.ShowDialog() = DialogResult.OK) using (FileStream fsWrite = new FileStream(sfd.FileName, FileMode.OpenOrCreate, FileAccess.Write) fsWrite.Write(buffer, 1024, r - 1024); ShowMsg("系统提示:", "保存文件成功!"); private void btnSendFile_Click
24、(object sender, EventArgs e) if (_socketSend = null | _socketSend.Connected = false) ShowMsg("系统提示:", "请先连接服务器,再发送消息!"); return; string endPoint = _socketSend.RemoteEndPoint.ToString(); OpenFileDialog ofd = new OpenFileDialog(); ofd.Filter = "所有文件|*.*" ofd.Title = "
25、;请选择要发送的文件" ofd.CheckFileExists = true; if (ofd.ShowDialog() = DialogResult.OK) string fileName = ofd.FileName; if (File.Exists(fileName) using (FileStream fsReader = new FileStream(fileName, FileMode.Open, FileAccess.Read) byte buffer = new byte1024 * 1024 * 5 + 1024; int r = fsReader.Read(buf
26、fer, 1024, buffer.Length - 1024); if (fsReader.Length < buffer.Length - 1024) buffer0 = 1; byte nameBuffer = Encoding.UTF8.GetBytes(Path.GetFileName(fileName); if (nameBuffer.Length > 1000) return; byte guidBuffer = Guid.NewGuid().ToByteArray(); guidBuffer.CopyTo(buffer, 1); nameBuffer.CopyTo(
27、buffer, 17); try _socketSend.Send(buffer, r + 1024, SocketFlags.None); ShowMsg("向" + endPoint + "发送:", "你给对方发送了文件: " + Path.GetFileName(fileName); catch (SocketException) else ShowMsg("系统消息:", "所选择的文件太大!"); else ShowMsg("系统消息:", "所选择的文
28、件不存在!"); (2)服务器:using System;using System.Collections.Generic;using System.ComponentModel;using System.Data;using System.Drawing;using System.IO;using System.Linq;using System.Net;using System.Net.Sockets;using System.Text;using System.Threading;using System.Threading.Tasks;using System.Windows
29、.Forms;namespace SocketStd public partial class Form1 : Form public Form1() InitializeComponent(); Socket _socketWatch;服务器启动监听: private void btnStart_Click(object sender, EventArgs e) if (_socketWatch = null) _socketWatch = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
30、 IPAddress ip = IPAddress.Any; IPEndPoint point = new IPEndPoint(ip, Convert.ToInt32(txtPoint.Text); _socketWatch.Bind(point); _socketWatch.Listen(10); ShowMsg("系统提示:", "监听成功!"); BeginSocket(_socketWatch); else ShowMsg("系统提示:", "已经开始监听了!"); private void BeginS
31、ocket(Socket socketWatch) SocketAsyncEventArgs sockete = new SocketAsyncEventArgs(); sockete.Completed += sockete_Completed; if (!socketWatch.AcceptAsync(sockete) if (sockete.AcceptSocket != null) CompletedSocket(sockete.AcceptSocket); / <summary> / 当连接成功时调用此方法 / </summary> / <param n
32、ame="acceptSocket">连接的Socket对象</param> private void CompletedSocket(Socket acceptSocket) BeginSocket(_socketWatch); string endPoint = acceptSocket.RemoteEndPoint.ToString(); if (SingleObject.GetSingle().ConnectedSocket.ContainsKey(endPoint) acceptSocket.Close(); ShowMsg("系统提示
33、:", "向" + endPoint + "的连接成功建立!"); SingleObject.GetSingle().ConnectedSocket.Add(endPoint, acceptSocket); while (true) /客户端连接成功后,服务器应该接受客户端发来的消息 byte buffer = new byte1024 * 1024 * 2; /实际接受到的有效字节数 int r = 0; try r = acceptSocket.Receive(buffer); catch (SocketException) r = 0;
34、if (r = 0) if (acceptSocket.Connected) ShowMsg("系统提示:", "向" + endPoint + "的连接断开!"); SingleObject.GetSingle().ConnectedSocket.Remove(endPoint); acceptSocket.Close(); break; if (buffer0 = 0) string str = Encoding.UTF8.GetString(buffer, 1, r - 1); ShowMsg(endPoint + "
35、:", str); else if (buffer0 = 1) string fileName = Encoding.UTF8.GetString(buffer, 17, 1000).Trim('0'); SingleObject.GetSingle().LastSendedFile = Path.GetTempFileName(); using (FileStream fsWrite = new FileStream(SingleObject.GetSingle().LastSendedFile, FileMode.OpenOrCreate, FileAccess.
36、Write) fsWrite.Write(buffer, 0, r); ShowMsg(endPoint + ":", "给你发送了文件:" + fileName); else if (buffer0 = 2) SingleObject.GetSingle().IsMove = true; else ShowMsg("系统消息:", "无法识别“" + endPoint + "”发送来的消息类型!"); private void Received() this.Activate(); priva
37、te void MoveForm() Received(); Random r = new Random(); Point location = this.Location; DateTime time = DateTime.Now; while (DateTime.Now - time) < TimeSpan.FromSeconds(1.5) Point nextPoint = new Point(location.X + r.Next(-10, 11), location.Y + r.Next(-10, 11); this.Location = nextPoint; System.T
38、hreading.Thread.Sleep(10); this.Location = location; void sockete_Completed(object sender, SocketAsyncEventArgs e) CompletedSocket(e.AcceptSocket); private void ShowMsg(string sender, string msg) string time = DateTime.Now.ToString("hh:mm:ss"); SingleObject.GetSingle().LogString.AppendLine(time + " " + sender); SingleObject.GetSingle().LogString.AppendLine(msg); SingleObject.GetSingle().LogString.
温馨提示
- 1. 本站所有资源如无特殊说明,都需要本地电脑安装OFFICE2007和PDF阅读器。图纸软件为CAD,CAXA,PROE,UG,SolidWorks等.压缩文件请下载最新的WinRAR软件解压。
- 2. 本站的文档不包含任何第三方提供的附件图纸等,如果需要附件,请联系上传者。文件的所有权益归上传用户所有。
- 3. 本站RAR压缩包中若带图纸,网页内容里面会有图纸预览,若没有图纸预览就没有图纸。
- 4. 未经权益所有人同意不得将文件中的内容挪作商业或盈利用途。
- 5. 人人文库网仅提供信息存储空间,仅对用户上传内容的表现方式做保护处理,对用户上传分享的文档内容本身不做任何修改或编辑,并不能对任何下载内容负责。
- 6. 下载文件中如有侵权或不适当内容,请与我们联系,我们立即纠正。
- 7. 本站不保证下载资源的准确性、安全性和完整性, 同时也不承担用户因使用这些下载资源对自己和他人造成任何形式的伤害或损失。
最新文档
- 人类与地表环境课件
- 数据结构与算法 课件 第八章查找
- 瑜伽课件教学课件
- 2024年内蒙古客运资格证专业知识试题答案
- 2024年宁夏客运从业资格证的考试题目及答案解析
- 2024年四川驾驶员客运从业资格证模拟考试题库答案
- 2024年邢台客运从业资格证考试
- 2024年邵阳客运从业资格证考试题
- 2024年长沙驾驶员客运资格证模拟考试题
- 2025届贵州省铜仁市第一中学数学高三第一学期期末检测试题含解析
- 船舶管理之—船舶防污染
- Creo原创教程(六) top-down-design之骨架模型 球阀建模举例
- 溢流面混凝土施工方案选择及施工方法浅谈
- (完整word版)化学实验室仪器药品清单
- 家庭农场项目建设方案3篇
- 医院非产科孕情管理和三病检测工作方案
- 物品出入库明细表格
- 柔性制造技术的五个类型
- 基于stm32的低频数字相位测量仪
- 第四章 造纸化学
- 湖南某粮食仓储扩建项目拱板屋面施工方案(附示意图)
评论
0/150
提交评论