上海大学计算机网络实验研究分析报告2_第1页
上海大学计算机网络实验研究分析报告2_第2页
上海大学计算机网络实验研究分析报告2_第3页
上海大学计算机网络实验研究分析报告2_第4页
上海大学计算机网络实验研究分析报告2_第5页
已阅读5页,还剩16页未读 继续免费阅读

下载本文档

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

文档简介

1、网络与通信课程实验报告实验2: Socket通信编程姓名 沈文潇院系计算机学院学号 13121602任课教师张瑞指导教师张瑞实验地点计706实验时间周四0304实验课表现出勤、表现得分(10)实验报告得分(40)实验总分操作结果得分(50)实验目地:.掌握Socket编程过程;.编写简单地网络应用程序.实验内容:利用你选择地任何一个编程语言,分别基于TCP和UDP编写一个简单地 Client/Server网络应用程序.具体程序要求参见实验指导书.要求以附件形式给出:系统概述:运行环境、编译、使用方法、实现环境、程序文件列表等;主要数据结构;主要算法描述;用户使用手册;程序源代码;实验要求:(学

2、生对预习要求地回答)(10分)|得分:Socket编程客户端地主要步骤TCP编程地客户端一般步骤是:1、创建一个 socket;2、设置socke墉性;3、绑定IP地址、端口等信息到 socket上;4、设置要连接地对方地IP地址和端口等属性;5、连接服务器;6、收发数据;7、关闭网络连接.UDP编程地客户端一般步骤是:1、创建一个 socket;2、设置socke墉性;3、绑定IP地址、端口等信息到 socket上;4、设置对方地IP地址和端口等属性;5、发送数据;6、关闭网络连接.Socket编程服务器端地主要步骤TCP编程地服务器端一般步骤是:1、创建一个socket2、设置socke墉

3、性;3、绑定IP地址、端口等信息到 socket上;4、开启监听;5、接收客户端上来地连接;6、收发数据;7、关闭网络连接;8、关闭监听.UDP编程地服务器端一般步骤是:1、创建一个 socket;2、设置socke墉性;3、绑定IP地址、端口等信息到 socket上;4、循环接收数据;5、关闭网络连接;实验过程中遇到地问题如何解决地?10分)得分:问题1:同步调用接收消息函数时,UI假死.问题描述:如果以单线程编程地逻辑,调用接收消息函数时,如果接收不到消息, 程序会停在这一步,相当 C语言编程时等待用户输入,这样一来界面将失去对用户操作地相应,造成UI假死.解决方案:TCP接收消息使用异步

4、调用,再通过回调函数来处理接收到地消息;UDP接收消息则采用开启接收消息地后台线程来防止UI假死.问题2:基于TCP协议地用户认证问题. TOC o 1-5 h z 问题描述:根据实验要求,连接时需要实现用户认证,但客户端与服务端建立连接地相关函 数里(基于.NET FrameWork 4.5地C#语言),并没有提供传递验证信息地参数或字段解决方案:服务端将先与客户端建立连接,但第一时间会发送给客户端消息:请求用户名和密码,客户端在收到这个消息时将第一时间想服务端提供用户输入地用户名和密码,如果客户端提供地用户名或密码不正确,或拒绝提供,服务端将主动断开与服务端地连接问题3:基于UDP地服务端

5、地接收消息线程无法终止.问题描述:UDP地服务端接收消息采用后台线程来处理,线程执行地函数是一个不同接收消息并处理地死循环,所以当程序主窗体关闭后,改线程无法正常终止解决方案:由于接收不到消息线程会一直停在那儿等待消息,故无法从外部通知线程主动终止,只能从外部强行杀死改线程,但这不是一个安全地方案本次实验地体会(结论)(10分)得分:平心而论此次实验课题地设计并不合理,如果按照大二正常地课程顺序学习,现在地我们并不具备 Socket编程地能力,即使我们能通过很短地时间,掌握实验指导书上地编程示 例,也不具备将其改写为图像化界面程序地能力,最早涉及到可视化编程地课程也只是本学期初学地Window

6、s编程,且刚掌握到简单控件地使用.因为我有幸在大二时提前选修了面向大三学生地.Net程序设计,才得以用 C#语言完成这次实验 我并不明白设计这个实验课题地老师地用意,或许是鼓励我们自学课程以外地知 识,或许是让我们短时间内掌握Socket编程,但可以肯定地是,我身边一些很优秀地同学将很难完成这个实验.所以学生在这里斗胆向老师提出建议,降低这个实验地要求,不鼓励使用图形界面, 而是统一写控制台程序来完成实验,这样我们将有机会把更多地精力放在学习Socket编程上,而不会因为不会做图形界面而吃亏思考题:(10分)思考题1: (4分)得分:你所用地编程语言在 Socket通信中用到地主要类及其主要作

7、用.System.Net.Sockets.Socket:实现 Berkeley 套接字接口 .System.Net.IPAddress :提供网际协议 (IP)地址.System.Net.Dns:提供简单地域名解析功能.System.Net.IPEndPoint :将网络端点表示为IP地址和端口号.System.Net.Sockets.UdpClient :提供用户数据报协议(UDP)网络服务.思考题2: (6分)而说明TCP和UDP编程地主要差异和特点.TCP面向连接通信,所以握手过程会消耗资源,过程为可靠连接,不会丢失数据,适合大 数据量交换,TCP协议能为应用程序提供可靠地通信连接,使一

8、台计算机发出地字节流无 差错地发往网络上地其他计算机,对可靠性要求高地数据通信系统往往使用TCP协议传输数据.UDP面向非可靠连接,会丢包,没有校验,速度快,无须握手过程,适用于一次只传送少 量数据、对可靠性要求不高地应用环境.指导教师评语:日期:附件:系统概述:运行环境、编译、使用方法、实现环境、程序文件列表等;运行环境:Windows7系统下地编译:C#使用方法:为一般窗口程序,双击即可实现环境:Microsoft Visio Studio程序文件列表:工解决方(4 个项目)J痼TCP服的 2 # Properties 4。App.confign* ClassDiagiramLcdA;。P

9、rogrammest 孑国 TcpServerFormxsJ占国TCP客户茸卜匕* Propertiest 引用gQ App a* Properties 引用uQ App.configa Cu Program.es /国 UdpSendForni*C5. m回UOP接修,Properties 引用 Q App.config n G Program.es 国 UdpRecuiv已Ftrm,c主要数据结构;TCP服务端:publicpartialclass TcpServerForm : Formprivate Socket _server;private Socket _client;priva

10、tebyte 口 _receiveData = newbyte1024;privatestring _username;privatestring _password;privatebool _needPasswordl;privatebool _passwordWrong;public TcpServerForm()privatevoid TcpReceiveForm_Load( object sender, EventArgs e) b5E2Rprivatevoid btnListen_Click( object sender, EventArgs e) p1Eanprivatevoid

11、btnDisconnect_Click( object sender, EventArgs e) DXDiTvoid AcceptedConnection( IAsyncResult iar)void ReceivedData( IAsyncResult iar)void SentData( IAsyncResult iar)void ProcessDisconnection()privatevoidtxtUserName_TextChanged( object sender,EventArgs e) RTCrpprivatevoidtxtPassword_TextChanged( objec

12、t sender,EventArgs e) 5PCzVprivatevoid lblUserName_Click( object sender, EventArgs e) jLBHr。privatevoid gnConnectInfo_Enter( object sender, EventArgs e) xHAQXprivatevoid lbMessage_SelectedIndexChanged( object sender, EventArgs e) LDAYtprivatevoid lbNativeIP_SelectedIndexChanged( object sender, Event

13、Args e) Zzz6Z。privatevoid lbConnectLog_SelectedIndexChanged( object sender, EventArgs e) dvzfv。TCP客户端:publicpartialclass TcpClientForm : FormSocket _client;byte 口 _receivedData = newbyte1024;public TcpClientForm()privatevoid btnConnect_Click( object sender, EventArgs e) rqyn1。privatevoid btnDisconne

14、ct_Click( object sender, EventArgs e) Emxv%privatevoid btnSend_Click( object sender, EventArgs e) SixE2。void Connected( IAsyncResult iar)void ReceivedData( IAsyncResult iar)void SentData( IAsyncResult iar)void ProcessDisconnection()privatevoid txtIP_TextChanged( object sender, EventArgs e) 6ewMyUDP接

15、收端:publicpartialclass UdpReceiveForm : Form privatebool ReadFlag = true ;private Thread th;private IPEndPoint remote;private UdpClient server;privateint count = 0;privatedouble num;public UdpReceiveForm()privatevoid read()privatevoid btnReceive_Click( object sender, EventArgs e) kavU4privatevoid Udp

16、ReceiveForm_FormClosing( object sender, FormClosingEventArgs e) y6V3A。 UDP发送端:publicpartialclassUdpSendForm Formpublic UdpSendForm()privatevoidbtnSend_Click( object sender,EventArgs e) M2ub6privatevoid txtIP_TextChanged( object sender, EventArgs e) 0YujC。privatevoidlblInfo_Click(object sender,EventA

17、rgs e) eUts8。异步调用与回调(部分):TCP服务端:_server.BeginAccept( newAsyncCallback (AcceptedConnection), _server); / 异步调用,开始接收 连接- void AcceptedConnection( IAsyncResult iar) sQsAE_client.BeginSend(sendMessage,0, sendMessage.Length, SocketFlags .None,newAsyncCallback (SentData), _client); / 异步调用,消息发送完毕执行-void Sen

18、tData( IAsyncResult iar) GMsIa_client.BeginReceive(_receiveData,0, _receiveData.Length, SocketFlags .None,newAsyncCallback (ReceivedData), _client); / 密码正确, 开始接收消息-void ReceivedData( IAsyncResult iar) TMRG。用户使用手册;TCP客户端、TCP服务端:1、用户打开TCP客户端并且输入服务端IP、用户名与密码(密码事先在服务端设置好);2、服务端点击“开始监听”,客户端点击“连接”;3、客户端在消

19、息框内输入消息,点击“发送” ,则消息发送到服务端,;4、服务端接收并且在“接收到地消息”框里显示消息与发送消息时地日期;注:客户端与服务端均能断开连接.一、 UDP发送端、UDP接收端:1、用户打开UDP发送端并且输入目标IP、需发送地消息;2、点击“发送按钮”;3、接收端点击“接收”则接收到消息 .程序源代码;Tcp服务端:using System;using System.Collections.Generic;using System.ComponentModel;using System.Data;using System.Drawing;using System.Linq;usin

20、g System.Text;using System.Threading.Tasks;using System.Windows.Forms;using System.Net;using System.Net.Sockets;namespaceTCP服务端publicpartialclass TcpServerForm : Formprivate Socket _server;private Socket _client;privatebyte 口 _receiveData = newbyte1024;privatestring _username;privatestring _password

21、;privatebool _needPasswordl;privatebool _passwordWrong;public TcpServerForm()InitializeComponent();privatevoid TcpReceiveForm_Load( object sender, EventArgs e) 7EqZc IPAddress 口 addressList = DnsGetHostAddresses( DnsGetHostName(); lzq7I。 foreach ( IPAddress ip in addressList) if (ip.ToString().Lengt

22、h = 15)lbNativeIP.Items.Insert(0, ip.ToString(); btnDisconnect.Enabled = false ; privatevoid btnListen_Click( object sender, EventArgs e) zvpge。_username = txtUserName.Text;_password = txtPassword.Text;/ 设置用户名与密码 NrpoJ。_server = neWSocket (AddressFamily .InterNetwork, SocketType.Stream, ProtocolType

23、 .Tcp); / 新建协议为tcp地socket 1nowfo_server.Bind(neWPEndPoint (IPAddress .Any, 8000); / 监听端口为 8000fjnFL。_server.Listen(5); / 开始监听_server.BeginAccept( newAsyncCallback (AcceptedConnection), _server); / 异步调用,开始接收 连接tfnNh。this .lblStatus.Text =开始监听.;btnListen.Enabled = false ; txtUserName.Enabled = false ;

24、 txtPassword.Enabled = false ; _needPasswordl = true ; _passwordWrong = false ; / 处理逻辑 privatevoid btnDisconnect_Click( object sender, EventArgs e) HbmVN _client.Close();_needPasswordl = true ;_server.BeginAccept( newAsyncCallback (AcceptedConnection), _server); V7l4j 。this .lblStatus.Text =开始监听.;vo

25、id AcceptedConnection( IAsyncResult iar) _client = ( Socket )iar.AsyncState).EndAccept(iar); / 终止接U连接 83lcP。this .lblStatus.Text =连接到:+ _client.RemoteEndPoint.ToString(); /解析对方地址与端口mZkkl。byte sendMessage = Encoding .Default.GetBytes( DateTime.Now.TimeOfDay + :请发送用户与密 码”);/向客户端提出发送密码地请求 AVktRo lbConn

26、ectLog.Items.Insert(0,连接到:+ _client.RemoteEndPoint.ToString(); ORjBi%_client.BeginSend(sendMessage, 0, sendMessage.Length, SocketFlags .None, newAsyncCallback (SentData), _client); / 异步调用,消息发送完毕执行 SentData2MiJT。btnDisconnect.Enabled = true ;void ReceivedData( IAsyncResult iar) _client = ( Socket )ia

27、r.AsyncState;int recv = 0;tryrecv = _client.EndReceive(iar);catchProcessDisconnection();/解析消息if (recv = 0)/ 解析失败_client.Close();this .IblStatus.Text =等待连接.”;_server.BeginAccept( newAsyncCallback (AcceptedConnection), _server); giiSp。return ;string receiveMessage = Encoding .Default.GetString(_receiv

28、eData, 0, recv);uEhOUthis .lbMessage.Items.Insert(O,receiveMessage); / 将消息放入消息歹U表 iAg9q。byte 口 feedbackMessage;if (_needPasswordl)string receiveUsername = receiveMessage.Substring(receiveMessage.LastIndexOf( : ) + 1, receiveMessage.IndexOf( # ) - (receiveMessage.LastIndexOf( : ) + 1); WwghWstring re

29、ceivePassword = receiveMessage.Substring(receiveMessage.IndexOf( #) + 1, receiveMessage.Length - (receiveMessage.IndexOf( #) + 1); asfps。if (receiveUsername = _username & receivePassword = _password)ooeyY。_needPasswordl = false ;_passwordWrong = false ;feedbackMessage = Encoding .Default.GetBytes( D

30、ateTime.Now.TimeOfDay + ”:验证成功”+receiveMessage); BkeGu_client.BeginSend(feedbackMessage, 0, feedbackMessage.Length, SocketFlags .None, newAsyncCallback (SentData), _client); PgdOQ return ; else this .lbConnectLog.Items.Insert(0, receiveUsername +# + receivePassword +验证失败);3cdXwfeedbackMessage = Enco

31、ding .Default.GetBytes( DateTime.Now.TimeOfDay + :验证失败+ receiveMessage); h8c52。_passwordWrong = true ;_client.BeginSend(feedbackMessage, 0, feedbackMessage.Length, SocketFlags .None, newAsyncCallback (SentData), _client); v4bdy。 return ; feedbackMessage = Encoding .Default.GetBytes( DateTime.Now.Tim

32、eOfDay + :成功接收+ receiveMessage); J0bm4_client.BeginSend(feedbackMessage, 0, feedbackMessage.Length, SocketFlags .None, newAsyncCallback (SentData), _client); XVauA void SentData( IAsyncResult iar) _client = ( Socket )iar.AsyncState;int sent = _client.EndSend(iar); if (_passwordWrong) lbConnectLog.It

33、ems.Insert(0,主动断开连接+ _client.RemoteEndPoint.ToString();bR9c6_client.Close(); _needPasswordl = true ;_server.BeginAccept( newAsyncCallback (AcceptedConnection), _server); / 重新开始接收新地连接pN9LBProcessDisconnection(); return ;_client.BeginReceive(_receiveData, 0, _receiveData.Length,SocketFlags .None,newAs

34、yncCallback (ReceivedData), _client); / 密码正确,开始接收消息 DJ8T7。void ProcessDisconnection() this .lblStatus.Text =已断开连接!重新监听.;lbConnectLog.Items.Insert(0,已经断开连接);this .btnDisconnect.Enabled =false ;privatevoid txtUserName_TextChanged( object sender, EventArgs e) QF81D privatevoid txtPassword_TextChanged(

35、object sender, EventArgs e) 4B7a9 privatevoid lblUserName_Click( object sender, EventArgs e) ix6iF 。 privatevoid gnConnectInfo_Enter( object sender, EventArgs e) wt6qb。 privatevoid lbMessage_SelectedIndexChanged( object sender, EventArgs e) Kp5zH privatevoid lbNativeIP_SelectedIndexChanged( object s

36、ender, EventArgs e) Yl4Hd。privatevoid lbConnectLog_SelectedIndexChanged( object sender, EventArgs e) ch4PJ。 TCP客户端:using System;using System.Collections.Generic;using System.ComponentModel;using System.Data;using System.Drawing;using System.Linq;using System.Text;using System.Threading.Tasks;using S

37、ystem.Windows.Forms;using System.Net;using System.Net.Sockets; namespaceTC哈户端 publicpartialclass TcpClientForm : Form Socket _client;byte 口 _receivedData =newbyte 1024;public TcpClientForm()InitializeComponent(); privatevoid btnConnect_Click( object sender, EventArgs e) qd3Yf。this .lblStatus.Text =连

38、接中.;_client = newSocket (AddressFamily .InterNetwork, SocketType.Stream, ProtocolType .Tcp); / 建立一个协议为TC地socket E836LIPEndPoint iep = neWPEndPoint (IPAddress .Parse( this .txtIP.Text), 8000); 设置端口为 8000s42eh。_client.BeginConnect(iep, newAsyncCallback (Connected), _client); 异步调用,开始连接服务 端 501nN。this .

39、btnConnect.Enabled = false ;this .btnDisconnect.Enabled = true ; privatevoid btnDisconnect_Click( object sender, EventArgs e)jW1vi。_client.Close();this .lblStatus.Text =连接断开!;this .btnConnect.Enabled = true ;this .btnDisconnect.Enabled = false ; privatevoid btnSend_Click( object sender, EventArgs e)

40、 xS0DO byte message = Encoding .Default.GetBytes( DateTime.Now.TimeOfDay + : +this .txtMessage.Text); /将文本框里地东西整合成消息 lozmk txtMessage.Focus();try _client.BeginSend(message, 0, message.Length, SocketFlags .None, newAsyncCallback (SentData), _client); / 开始发送 ZKZUQ txtMessage.Clear();catch ProcessDisco

41、nnection();return ; void Connected( lAsyncResult iar)_client = ( Socket )iar.AsyncState; try _client.EndConnect(iar); / 关闭连接请求this .lblStatus.Text =连接到:+ _client.RemoteEndPoint.ToString();dGY2m_client.BeginReceive(_receivedData, 0, _receivedData.Length,SocketFlags .None,newAsyncCallback (ReceivedDat

42、a), _client); /异步调用,开始接收消息 rCYbS catchProcessDisconnection();return ; void ReceivedData( IAsyncResult iar) Socket remote = ( Socket )iar.AsyncState;int recv; try recv = remote.EndReceive(iar);catchProcessDisconnection();return ;if (recv = 0)_client.Close();ProcessDisconnection();return ;string recei

43、veMessage = Encoding .Default.GetString(_receivedData, 0, recv);/ 将收至U地消息处理为字符串FyXjo。this .lbMessage.Items.Insert(0, receiveMessage); / 将收到地消息放到消息列表 TuWrUif (receiveMessage.Substring(receiveMessage.LastIndexOf( : ) + 1, receiveMessage.Length - (receiveMessage.LastIndexOf( : ) + 1)=请发送用户与密码)7qWAqbyte

44、 usernameAndPassword = Encoding .Default.GetBytes( DateTime.Now.TimeOfDay + : +txtUserName.Text +# + txtPassword.Text).ToArray(); llVIW。try _client.BeginSend(usernameAndPassword, 0, usernameAndPassword.Length, SocketFlags .None, newAsyncCallback (SentData), _client); / 向服务端发送用户名和密码 yhUQs catchProces

45、sDisconnection();return ; /try _client.BeginReceive(_receivedData, 0, _receivedData.Length,SocketFlags .None,newAsyncCallback (ReceivedData), _client); MdUZY catch ProcessDisconnection(); return ; void SentData( IAsyncResult iar) Socket remote = ( Socket )iar.AsyncState; int sent = remote.EndSend(ia

46、r); try remote.BeginReceive(_receivedData, 0, _receivedData.Length,SocketFlags .None,newAsyncCallback (ReceivedData), remote);09T7t。 catch ProcessDisconnection(); return ; void ProcessDisconnection() this .lblStatus.Text =发送端已经断开连接,或者接收端已经关闭!请重新尝试连接! ; e5TfZthis .btnConnect.Enabled = true ; btnDisco

47、nnect.Enabled = false ;privatevoid txtIP_TextChanged( object sender, EventArgs e) siSov。 UDP发送端:using System;using System.Collections.Generic;using System.ComponentModel;using System.Data;using System.Drawing;using System.Text;using System.Windows.Forms;using System.Net;using System.Net.Sockets;/usi

48、ng System.Threading;namespaceUDPt送端 publicpartialclass UdpSendForm Form public UdpSendForm()InitializeComponent();privatevoid btnSend_Click( object sender, EventArgs e) GXRw1/创建UD啊络服务UdpClient SendUdp = newUdpClient ();IPAddress remotelP;/判断IP地址地正确性 tryremotelP = IPAddress .Parse(txtlP.Text); catchM

49、essageBoxShow(请输入正确地IP地址!,错误); return ;IPEndPoint remoteep = neWPEndPoint (remoteIP, 8010);/ 端口设置为 8010UTRExByte buffer = null ;Encoding enc = Encoding .Unicode;buffer = enc.GetBytes(txtMessage.Text.ToCharArray(); / 将此实例中地字符复制到 Unicode 字 符数组.8PQN3/传送信息到指定计算机地8010端口号SendUdp.Send(buffer, buffer.Length

50、, remoteep); / 发送消息 mLPVz privatevoid txtIP_TextChanged( object sender, EventArgs e) AHP35 privatevoid lblInfo_Click( object sender, EventArgs e) NDOcB UDP接收端:using System;using System.Collections.Generic;using System.ComponentModel;using System.Data;using System.Drawing;using System.Text;using Syst

51、em.Windows.Forms;using System.Net;using System.Net.Sockets;Formusing System.Threading; namespaceUD艰收端 publicpartialclass UdpReceiveForm : privatebool ReadFlag = true ; private Thread th;private IPEndPoint remote;private UdpClient server;privateint count = 0;privatedouble num;public UdpReceiveForm()InitializeComponent(); privatevoid read() tryserver = newUdpClient (8010); / 创建端口为 8010地socketcatchMessageBoxShow(创建端口失败!,错误);return ;Enc

温馨提示

  • 1. 本站所有资源如无特殊说明,都需要本地电脑安装OFFICE2007和PDF阅读器。图纸软件为CAD,CAXA,PROE,UG,SolidWorks等.压缩文件请下载最新的WinRAR软件解压。
  • 2. 本站的文档不包含任何第三方提供的附件图纸等,如果需要附件,请联系上传者。文件的所有权益归上传用户所有。
  • 3. 本站RAR压缩包中若带图纸,网页内容里面会有图纸预览,若没有图纸预览就没有图纸。
  • 4. 未经权益所有人同意不得将文件中的内容挪作商业或盈利用途。
  • 5. 人人文库网仅提供信息存储空间,仅对用户上传内容的表现方式做保护处理,对用户上传分享的文档内容本身不做任何修改或编辑,并不能对任何下载内容负责。
  • 6. 下载文件中如有侵权或不适当内容,请与我们联系,我们立即纠正。
  • 7. 本站不保证下载资源的准确性、安全性和完整性, 同时也不承担用户因使用这些下载资源对自己和他人造成任何形式的伤害或损失。

评论

0/150

提交评论