資源描述:
《c#完整通信代碼(點對點,點對多,同步,異步,udp,tcp)》由會員上傳分享,免費在線閱讀,更多相關(guān)內(nèi)容在行業(yè)資料-天天文庫。
1、C#完整的通信代碼(點對點,點對多,同步,異步,UDP,TCP)C#完整的通信代碼(點對點,點對多,同步,異步,UDP,TCP).txtC#codenamespaceUDPServer{classProgram{staticvoidMain(string[]args){intrecv;byte[]data=newbyte[1024];//構(gòu)建TCP服務(wù)器//得到本機IP,設(shè)置TCP端口號IPEndPointipep=newIPEndPoint(IPAddress.Any,8001);Socketnewsock=newSocket(AddressFamily.InterNetwork,Socke
2、tType.Dgram,ProtocolType.Udp);//綁定網(wǎng)絡(luò)地址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,refR
3、emote);Console.WriteLine("Messagereceivedfrom{0}:",Remote.ToString());Console.WriteLine(Encoding.ASCII.GetString(data,0,recv));//客戶機連接成功后,發(fā)送歡迎信息stringwelcome="Welcome!";//字符串與字節(jié)數(shù)組相互轉(zhuǎn)換data=Encoding.ASCII.GetBytes(welcome);//發(fā)送信息newsock.SendTo(data,data.Length,SocketFlags.None,Remote);while(true){data
4、=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.Collections.Generic;usingSystem.Linq;usingSystem.Text;usingSystem.Net;usingSystem.Net.Sockets;n
5、amespaceUDPClient{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端口號IPEndPointipep=newIPEndPoint(IPAddress.Parse("127.0.0.1"),8001);//定義網(wǎng)絡(luò)類型,數(shù)據(jù)連接類型和網(wǎng)絡(luò)協(xié)議UDPSocketserve
6、r=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=serv
7、er.ReceiveFrom(data,refRemote);Console.WriteLine("Messagereceivedfrom{0}:",Remote.ToString());Console.WriteLine(Encoding.ASCII.GetString(data,0,recv));while(true){input=Console.ReadLine();if(input=="e