C#基于TCP的客户端服务器通信_第1页
C#基于TCP的客户端服务器通信_第2页
C#基于TCP的客户端服务器通信_第3页
C#基于TCP的客户端服务器通信_第4页
C#基于TCP的客户端服务器通信_第5页
已阅读5页,还剩19页未读 继续免费阅读

下载本文档

版权说明:本文档由用户提供并上传,收益归属内容提供方,若内容存在侵权,请进行举报或认领

文档简介

1、 高级网络程序设计课程设计报告题 目 基于TCP的局域网即时消息系统的客户端和服务器端的设计与实现学 号 姓 名 计算机网络工程教研室2016年01月11 日21目 录一、课程设计内容.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 Sy

4、stem.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 p

5、ublic 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

6、.Parse(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、("系统提示:", "已经连接到服务器:" + _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

9、(buffer); 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

11、.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(); priv

12、ate 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.

13、Threading.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 basicB

14、uffer = 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().Log

16、String.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.T

17、oString(); 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 = t

18、rue; private void btnClose_Click(object sender, EventArgs e) if (_socketSend != null | _socketSend.Connected = true) ShowMsg("系统提示:", "服务器已经断开或未连接!"); return; try ShowMsg("系统提示:", "向" + _socketSend.RemoteEndPoint.ToString() + "的连接断开!"); _socketSend.C

19、lose(); 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

20、_socketSend.Send(buffer); ShowMsg("向" + endPoint + "发送:", "你给对方发送了一个震动!"); catch (SocketException) MoveForm(); private void btnReceiveFile_Click(object sender, EventArgs e) if (string.IsNullOrEmpty(SingleObject.GetSingle().LastSendedFile) ShowMsg("系统提示:", &quo

21、t;目前没有接收到任何的文件!"); 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 < g

22、uidb.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_Cli

24、ck(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 = &qu

25、ot;请选择要发送的文件" 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(b

26、uffer, 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.CopyT

27、o(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.Windo

29、ws.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 Begi

31、nSocket(Socket socketWatch) SocketAsyncEventArgs sockete = new SocketAsyncEventArgs(); sockete.Completed += sockete_Completed; if (!socketWatch.AcceptAsync(sockete) if (sockete.AcceptSocket != null) CompletedSocket(sockete.AcceptSocket); / <summary> / 当连接成功时调用此方法 / </summary> / <param

32、 name="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 + &quo

35、t;:", 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, FileAcces

36、s.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(); pri

37、vate 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

38、.Threading.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. 本站不保证下载资源的准确性、安全性和完整性, 同时也不承担用户因使用这些下载资源对自己和他人造成任何形式的伤害或损失。

评论

0/150

提交评论