C完整的通信代码(点对点_点对多_同步_异步_UDP_TCP).pdf
![资源得分’ title=](/images/score_1.gif)
![资源得分’ title=](/images/score_1.gif)
![资源得分’ title=](/images/score_1.gif)
![资源得分’ title=](/images/score_1.gif)
![资源得分’ title=](/images/score_05.gif)
《C完整的通信代码(点对点_点对多_同步_异步_UDP_TCP).pdf》由会员分享,可在线阅读,更多相关《C完整的通信代码(点对点_点对多_同步_异步_UDP_TCP).pdf(44页珍藏版)》请在淘文阁 - 分享文档赚钱的网站上搜索。
1、C#完整的通信代码(点对点,点对多,同步,异步,UDP,TCP).txt 我这人从不记仇,一般有仇当场我就报了。没什么事不要找我,有事更不用找我!就算是 believe 中间也藏了一个 lie!我那么喜欢你,你喜欢我一下会死啊?我又不是人民币,怎么能让人人都喜欢我?C#codenamespace UDPServerclass Programstatic void Main(string args)int recv;byte data=new byte1024;/构建 TCP 服务器/得到本机 IP,设置 TCP 端口号IPEndPoint ipep=new IPEndPoint(IPAddre
2、ss.Any,8001);Socketnewsock=newSocket(AddressFamily.InterNetwork,SocketType.Dgram,ProtocolType.Udp);/绑定网络地址newsock.Bind(ipep);Console.WriteLine(ThisisaServer,hostnameis0,Dns.GetHostName();/等待客户机连接Console.WriteLine(Waiting for a client.);/得到客户机 IPIPEndPoint sender=new IPEndPoint(IPAddress.Any,0);EndPo
3、int Remote=(EndPoint)(sender);recv=newsock.ReceiveFrom(data,ref Remote);Console.WriteLine(Message received from 0:,Remote.ToString();Console.WriteLine(Encoding.ASCII.GetString(data,0,recv);/客户机连接成功后,发送欢迎信息string welcome=Welcome!;/字符串与字节数组相互转换data=Encoding.ASCII.GetBytes(welcome);/发送信息newsock.SendTo(
4、data,data.Length,SocketFlags.None,Remote);while(true)data=new byte 1024;/发送接受信息recv=newsock.ReceiveFrom(data,ref Remote);Console.WriteLine(Encoding.ASCII.GetString(data,0,recv);newsock.SendTo(data,recv,SocketFlags.None,Remote);C#codeusing System;using System.Collections.Generic;using System.Linq;usi
5、ng System.Text;using System.Net;using System.Net.Sockets;namespace UDPClientclass Programstatic void Main(string args)byte data=new byte1024;string input,stringData;/构建 TCP 服务器Console.WriteLine(ThisisaClient,hostnameis0,Dns.GetHostName();/设置服务 IP,设置 TCP 端口号IPEndPoint ipep=new IPEndPoint(IPAddress.Pa
6、rse(127.0.0.1),8001);/定义网络类型,数据连接类型和网络协议 UDPSocketserver=newSocket(AddressFamily.InterNetwork,SocketType.Dgram,ProtocolType.Udp);string welcome=Hello!;data=Encoding.ASCII.GetBytes(welcome);server.SendTo(data,data.Length,SocketFlags.None,ipep);IPEndPoint sender=new IPEndPoint(IPAddress.Any,0);EndPoin
7、t Remote=(EndPoint)sender;data=new byte1024;int recv=server.ReceiveFrom(data,ref Remote);Console.WriteLine(Message received from 0:,Remote.ToString();Console.WriteLine(Encoding.ASCII.GetString(data,0,recv);while(true)input=Console.ReadLine();if(input=exit)break;server.SendTo(Encoding.ASCII.GetBytes(
8、input),Remote);data=new byte 1024;recv=server.ReceiveFrom(data,ref Remote);stringData=Encoding.ASCII.GetString(data,0,recv);Console.WriteLine(stringData);Console.WriteLine(Stopping Client.);server.Close();C#codeTCPClientTCPClient 类提供了一种使用TCP 协议连接到某个端点的简化方法。它还通过NetworkStream 对象展现在连接过程中读取或写入的数据。请参见下面从
9、 QuickStart 文档中摘录的日期/时间客户机示例。使用 C#编写using System;using System.Net;using System.Net.Sockets;using System.IO;using System.Text;class Clientpublic static void Main(String args)TCPClient tcpc=new TCPClient();Byte read=new Byte32;if(args.Length!=1)Console.WriteLine(“请在命令行中指定服务器名称”);return;String server=a
10、rgs0;/验证服务器是否存在if(DNS.GetHostByName(server)=null)Console.WriteLine(“找不到服务器:”+服务器);return;/尝试连接到服务器if(tcpc.Connect(server,13)=-1)Console.WriteLine(“无法连接到服务器:”+服务器);return;/获取流Stream s=tcpc.GetStream();/读取流并将它转换为 ASCII 码形式int bytes=s.Read(read,0,read.Length);String Time=Encoding.ASCII.GetString(read);
11、/显示数据Console.WriteLine(“已接收到的”+字节+“字节”);Console.WriteLine(“当前日期和时间是:”+时间);tcpc.Close();TCPListenerTCPListener 类便于在来自某个客户机的 TCP 连接的特定套接字上进行侦听的工作。请参见下面包括在 QuickStart 文档中的日期/时间服务器示例。使用 C#编写using System;using System.Net;using System.Net.Sockets;using System.Text;class Serverpublic static void Main()Date
12、Time now;String strDateLine;Encoding ASCII=Encoding.ASCII;/在端口 13 进行侦听TCPListener tcpl=new TCPListener(13);tcpl.Start();Console.WriteLine(“正在等待客户进行连接”);Console.WriteLine(“请按 Ctrl+c 退出.”);while(true)/接收会阻塞,直到有人连接上Socket s=tcpl.Accept();/获取当前的日期和时间并将它连接成一个字符串now=DateTime.Now;strDateLine=now.ToShortDat
13、eString()+now.ToLongTimeString();/将该字符串转换成一个字节数组并发送它Byte byteDateLine=ASCII.GetBytes(strDateLine.ToCharArray();s.Send(byteDateLine,byteDateLine.Length,0);Console.WriteLine(“发送”+strDateLine);#region Download:File transfer FROM ftp server/Copy a file from FTP server to local/Target filename,if require
14、d/Full path of the local file/Target can be blank(use same filename),or just a filename/(assumes current directory)or a full path and filename public bool Download(string sourceFilename,string localFilename,boolPermitOverwrite)/2.determine target fileFileInfo fi=new FileInfo(localFilename);return th
15、is.Download(sourceFilename,fi,PermitOverwrite);/Version taking an FtpFileInfopublicboolDownload(FtpFileInfofile,stringlocalFilename,boolpermitOverwrite)return this.Download(file.FullName,localFilename,permitOverwrite);/Another version taking FtpFileInfo and FileInfopublicboolDownload(FtpFileInfofile
16、,FileInfolocalFI,boolpermitOverwrite)return this.Download(file.FullName,localFI,permitOverwrite);/Version taking string/FileInfopublicboolDownload(stringsourceFilename,FileInfotargetFI,boolpermitOverwrite)/1.check targetif(targetFI.Exists&!(permitOverwrite)throw(new ApplicationException(Target file
17、already exists);/2.check sourcestring target;if(sourceFilename.Trim()=)throw(new ApplicationException(File not specified);else if(sourceFilename.Contains(/)/treat as a full pathtarget=AdjustDir(sourceFilename);else/treat as filename only,use current directorytarget=CurrentDirectory+sourceFilename;st
18、ring URI=Hostname+target;/3.perform copySystem.Net.FtpWebRequest ftp=GetRequest(URI);/Set request to download a file in binary modeftp.Method=System.Net.WebRequestMethods.Ftp.DownloadFile;ftp.UseBinary=true;/open request and get response streamusing(FtpWebResponse response=(FtpWebResponse)ftp.GetRes
19、ponse()using(Stream responseStream=response.GetResponseStream()/loop to read&write to fileusing(FileStream fs=targetFI.OpenWrite()trybyte buffer=new byte2048;int read=0;doread=responseStream.Read(buffer,0,buffer.Length);fs.Write(buffer,0,read);while(!(read=0);responseStream.Close();fs.Flush();fs.Clo
20、se();catch(Exception)/catch error and delete file only partially downloadedfs.Close();/delete target file as its incompletetargetFI.Delete();throw;responseStream.Close();response.Close();return true;#endregion简单的 UDP 收发.发送C#codetrySockets=newSocket(AddressFamily.InterNetwork,SocketType.Dgram,Protoco
21、lType.Udp);/向此网段发广播包int UDPListenerPort=8082;IPAddress broadcast=IPAddress.Parse(192.168.0.255);/此处根据 IP 及子网掩码改为相应的广播 IPstring ts=This is UPD string for sending;byte sendbuf=Encoding.ASCII.GetBytes(ts);IPEndPointep=newIPEndPoint(broadcast,UDPListenerPort);s.SendTo(sendbuf,ep);catch(Exception e)接收C#c
22、odeUdpClient listener;int UDPListenerPort=8082;IPEndPoint groupEP=new IPEndPoint(IPAddress.Any,UDPListenerPort);trywhile(true)byte bytes=listener.Receive(ref groupEP);stringRecIP=groupEP.ToString().Substring(0,groupEP.ToString().IndexOf(:);/收到发送 UPD 端的 IPstringRecStr=Encoding.ASCII.GetString(bytes,0
23、,bytes.Length);/收到的 UPD 字符串catchC#codeTCPClientTCPClient 类提供了一种使用TCP 协议连接到某个端点的简化方法。它还通过NetworkStream 对象展现在连接过程中读取或写入的数据。请参见下面从 QuickStart 文档中摘录的日期/时间客户机示例。使用 C#编写using System;using System.Net;using System.Net.Sockets;using System.IO;using System.Text;class Clientpublic static void Main(String args)
24、TCPClient tcpc=new T来一个 Remoting 的:C#codeusing System;namespace Remotablepublic class RemotableType:MarshalByRefObjectprivate string _internalString=This is the RemotableType.;public string StringMethod()return _internalString;using System;using System.Runtime.Remoting;namespace RemotingFirstpublic
25、class Listenerpublic static void Main()RemotingConfiguration.Configure(Listener.exe.config);Console.WriteLine(Listening for requests.Press Enter to exit);Console.ReadLine();using System;using System.Runtime.Remoting;namespace Clientpublic class Clientpublic static void Main()RemotingConfiguration.Co
- 配套讲稿:
如PPT文件的首页显示word图标,表示该PPT已包含配套word讲稿。双击word图标可打开word文档。
- 特殊限制:
部分文档作品中含有的国旗、国徽等图片,仅作为作品整体效果示例展示,禁止商用。设计者仅对作品中独创性部分享有著作权。
- 关 键 词:
- 完整 通信 代码 点对点 同步 异步 _UDP_TCP
![提示](https://www.taowenge.com/images/bang_tan.gif)
限制150内