您好,欢迎访问三七文档
当前位置:首页 > 电子/通信 > 综合/其它 > C#完整的通信代码(点对点-点对多-同步-异步-UDP-TCP)
C#codenamespaceUDPServer{classProgram{staticvoidMain(string[]args){intrecv;byte[]data=newbyte[1024];//构建TCP服务器//得到本机IP,设置TCP端口号IPEndPointipep=newIPEndPoint(IPAddress.Any,8001);Socketnewsock=newSocket(AddressFamily.InterNetwork,SocketType.Dgram,ProtocolType.Udp);//绑定网络地址newsock.Bind(ipep);Console.WriteLine(ThisisaServer,hostnameis{0},Dns.GetHostName());//等待客户机连接Console.WriteLine(Waitingforaclient...);//得到客户机IPIPEndPointsender=newIPEndPoint(IPAddress.Any,0);EndPointRemote=(EndPoint)(sender);recv=newsock.ReceiveFrom(data,refRemote);Console.WriteLine(Messagereceivedfrom{0}:,Remote.ToString());Console.WriteLine(Encoding.ASCII.GetString(data,0,recv));//客户机连接成功后,发送欢迎信息stringwelcome=Welcome!;//字符串与字节数组相互转换data=Encoding.ASCII.GetBytes(welcome);//发送信息newsock.SendTo(data,data.Length,SocketFlags.None,Remote);while(true){data=newbyte[1024];//发送接受信息recv=newsock.ReceiveFrom(data,refRemote);Console.WriteLine(Encoding.ASCII.GetString(data,0,recv));newsock.SendTo(data,recv,SocketFlags.None,Remote);}}}}C#codeusingSystem;usingSystem.Collections.Generic;usingSystem.Linq;usingSystem.Text;usingSystem.Net;usingSystem.Net.Sockets;namespaceUDPClient{classProgram{staticvoidMain(string[]args){byte[]data=newbyte[1024];stringinput,stringData;//构建TCP服务器Console.WriteLine(ThisisaClient,hostnameis{0},Dns.GetHostName());//设置服务IP,设置TCP端口号IPEndPointipep=newIPEndPoint(IPAddress.Parse(127.0.0.1),8001);//定义网络类型,数据连接类型和网络协议UDPSocketserver=newSocket(AddressFamily.InterNetwork,SocketType.Dgram,ProtocolType.Udp);stringwelcome=Hello!;data=Encoding.ASCII.GetBytes(welcome);server.SendTo(data,data.Length,SocketFlags.None,ipep);IPEndPointsender=newIPEndPoint(IPAddress.Any,0);EndPointRemote=(EndPoint)sender;data=newbyte[1024];intrecv=server.ReceiveFrom(data,refRemote);Console.WriteLine(Messagereceivedfrom{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(input),Remote);data=newbyte[1024];recv=server.ReceiveFrom(data,refRemote);stringData=Encoding.ASCII.GetString(data,0,recv);Console.WriteLine(stringData);}Console.WriteLine(StoppingClient.);server.Close();}}}C#codeTCPClientTCPClient类提供了一种使用TCP协议连接到某个端点的简化方法。它还通过NetworkStream对象展现在连接过程中读取或写入的数据。请参见下面从QuickStart文档中摘录的日期/时间客户机示例。使用C#编写usingSystem;usingSystem.Net;usingSystem.Net.Sockets;usingSystem.IO;usingSystem.Text;classClient{publicstaticvoidMain(String[]args){TCPClienttcpc=newTCPClient();Byte[]read=newByte[32];if(args.Length!=1){Console.WriteLine(“请在命令行中指定服务器名称”);return;}Stringserver=args[0];//验证服务器是否存在if(DNS.GetHostByName(server)==null){Console.WriteLine(“找不到服务器:”+服务器);return;}//尝试连接到服务器if(tcpc.Connect(server,13)==-1){Console.WriteLine(“无法连接到服务器:”+服务器);return;}//获取流Streams=tcpc.GetStream();//读取流并将它转换为ASCII码形式intbytes=s.Read(read,0,read.Length);StringTime=Encoding.ASCII.GetString(read);//显示数据Console.WriteLine(“已接收到的”+字节+“字节”);Console.WriteLine(“当前日期和时间是:”+时间);tcpc.Close();}}TCPListenerTCPListener类便于在来自某个客户机的TCP连接的特定套接字上进行侦听的工作。请参见下面包括在QuickStart文档中的日期/时间服务器示例。使用C#编写usingSystem;usingSystem.Net;usingSystem.Net.Sockets;usingSystem.Text;classServer{publicstaticvoidMain(){DateTimenow;StringstrDateLine;EncodingASCII=Encoding.ASCII;//在端口13进行侦听TCPListenertcpl=newTCPListener(13);tcpl.Start();Console.WriteLine(“正在等待客户进行连接”);Console.WriteLine(“请按Ctrl+c退出...”);while(true){//接收会阻塞,直到有人连接上Sockets=tcpl.Accept();//获取当前的日期和时间并将它连接成一个字符串now=DateTime.Now;strDateLine=now.ToShortDateString()++now.ToLongTimeString();//将该字符串转换成一个字节数组并发送它Byte[]byteDateLine=ASCII.GetBytes(strDateLine.ToCharArray());s.Send(byteDateLine,byteDateLine.Length,0);Console.WriteLine(“发送”+strDateLine);}}}#regionDownload:FiletransferFROMftpserver///summary///CopyafilefromFTPservertolocal////summary///paramname=sourceFilenameTargetfilename,ifrequired/param///paramname=localFilenameFullpathofthelocalfile/param///returns/returns///remarksTargetcanbeblank(usesamefilename),orjustafilename///(assumescurrentdirectory)orafullpathandfilename/remarkspublicboolDownload(stringsourceFilename,stringlocalFilename,boolPermitOverwrite){//2.determinetargetfileFileInfofi=newFileInfo(localFilename);returnthis.Download(sourceFilename,fi,PermitOverwrite);}//VersiontakinganFtpFileInfopublicboolDownload(FtpFileInfofile,stringlocalFilename,boolpermitOverwrite){returnthis.Download(file.FullName,localFilename,permitOverwrite);}//AnotherversiontakingFtpFileInfoandFileInfopublicboolDownload(FtpFileInfofile,FileInfolocalFI,boolpermitOverwrite){returnthis.Download(file.FullName,localFI,permitOverwrite);}//Versiontakingstring/FileInfopublicboolDownload(stringsourceFilename,FileInfotargetFI,boolpermitOverwrite){//1.checktargetif(targetFI.Exists&&!(permitOverwrite)){throw(newApplicationException(Targetfilealreadyexists));}//2.checksourcestringtarget;if(sourceFilename.Trim()==){throw(newApplicationException(Filenotspecified));}elseif(sourceFilename.Contains(/)){//treatasafullpathtarget=AdjustDir(sourceFilename);}else{//treatasfilenameonly,usecurrent
本文标题:C#完整的通信代码(点对点-点对多-同步-异步-UDP-TCP)
链接地址:https://www.777doc.com/doc-2933044 .html