資源描述:
《c完整的通信代碼點(diǎn)對(duì)點(diǎn),點(diǎn)對(duì)多,同步,異步,udp,》由會(huì)員上傳分享,免費(fèi)在線閱讀,更多相關(guān)內(nèi)容在應(yīng)用文檔-天天文庫(kù)。
1、C#完整的通信代碼(點(diǎn)對(duì)點(diǎn),點(diǎn)對(duì)多,同步,異步,UDP,TCP).txt20如果你努力去發(fā)現(xiàn)美好,美好會(huì)發(fā)現(xiàn)你;如果你努力去尊重他人,你也會(huì)獲得別人尊重;如果你努力去幫助他人,你也會(huì)得到他人的幫助?!∩拖褚环N回音,你送出什么它就送回什么,你播種什么就收獲什么,你給予什么就得到什么。C#codenamespaceUDPServer{classProgram{staticvoidMain(string[]args){intrecv;byte[]data=newbyte[1024];//構(gòu)建TCP服務(wù)器//得到本機(jī)IP,設(shè)置TCP端口號(hào)IPEndPointipep=newIPEndPoi
2、nt(IPAddress.Any,8001);Socketnewsock=newSocket(AddressFamily.InterNetwork,SocketType.Dgram,ProtocolType.Udp);//綁定網(wǎng)絡(luò)地址newsock.Bind(ipep);Console.WriteLine("ThisisaServer,hostnameis{0}",Dns.GetHostName());//等待客戶機(jī)連接Console.WriteLine("Waitingforaclient...");//得到客戶機(jī)IPIPEndPointsender=newIPEndPoint(IP
3、Address.Any,0);EndPointRemote=(EndPoint)(sender);recv=newsock.ReceiveFrom(data,refRemote);Console.WriteLine("Messagereceivedfrom{0}:",Remote.ToString());Console.WriteLine(Encoding.ASCII.GetString(data,0,recv));//客戶機(jī)連接成功后,發(fā)送歡迎信息stringwelcome="Welcome!";//字符串與字節(jié)數(shù)組相互轉(zhuǎn)換data=Encoding.ASCII.GetBytes(w
4、elcome);//發(fā)送信息newsock.SendTo(data,data.Length,SocketFlags.None,Remote);while(true){data=newbyte[1024];//發(fā)送接受信息recv=newsock.ReceiveFrom(data,refRemote);Console.WriteLine(Encoding.ASCII.GetString(data,0,recv));newsock.SendTo(data,recv,SocketFlags.None,Remote);}}}}C#codeusingSystem;usingSystem.Coll
5、ections.Generic;usingSystem.Linq;usingSystem.Text;usingSystem.Net;usingSystem.Net.Sockets;namespaceUDPClient{classProgram{staticvoidMain(string[]args){byte[]data=newbyte[1024];stringinput,stringData;//構(gòu)建TCP服務(wù)器Console.WriteLine("ThisisaClient,hostnameis{0}",Dns.GetHostName());//設(shè)置服務(wù)IP,設(shè)置TCP端口號(hào)IPE
6、ndPointipep=newIPEndPoint(IPAddress.Parse("127.0.0.1"),8001);//定義網(wǎng)絡(luò)類型,數(shù)據(jù)連接類型和網(wǎng)絡(luò)協(xié)議UDPSocketserver=newSocket(AddressFamily.InterNetwork,SocketType.Dgram,ProtocolType.Udp);stringwelcome="Hello!";data=Encoding.ASCII.GetBytes(welcome);server.SendTo(data,data.Length,SocketFlags.None,ipep);IPEndPointse
7、nder=newIPEndPoint(IPAddress.Any,0);EndPointRemote=(EndPoint)sender;data=newbyte[1024];intrecv=server.ReceiveFrom(data,refRemote);Console.WriteLine("Messagereceivedfrom{0}:",Remote.ToString());Console.WriteLine(Encoding.ASCI