这些天由于有个pp的项目于是恶补了一下自己在网络编程方面的知识下面一个程序是我在这过程中的一个很小的程序想看看这个udp协议是不是适合做pp如果哪位朋友是做pp的请不吝赐教! 下面将我自己的代码贴出来希望各位指正! using System; using SystemCollectionsGeneric; using SystemText; using SystemNet; using SystemNetSockets; using SystemThreading; namespace UDPChat { class Program { private static IPAddress remoteAddress; private static int remotePort; private static int localPort; [STAThread ] static void Main(string[] args) { try { ConsoleWrite(Enter Local Port); localPort = ConvertToInt(ConsoleReadLine()); ConsoleWrite(Enter Remote Port); remotePort = ConvertToInt(ConsoleReadLine()); ConsoleWrite(Enter Remote IP address); remoteAddress = IPAddressParse(ConsoleReadLine()); Thread tRec = new Thread(new ThreadStart(Receiver)); tRecStart(); while (true) { Send(ConsoleReadLine()); } } catch (Exception ex) { ConsoleWriteLine(exToString ()); } } private static void Send(string p) { UdpClient sender = new UdpClient(); IPEndPoint endPoint = new IPEndPoint(remoteAddress remotePort ); try { byte[] bytes = EncodingASCIIGetBytes(p); senderSend(bytes bytesLength endPoint); } catch (Exception ex) { ConsoleWriteLine(exToString()); } finally { senderClose(); } } public static void Receiver() { UdpClient receivingUdpClient = new UdpClient(localPort); IPEndPoint remoteiendpoint = null; try { ConsoleWriteLine(Ready For Chat!!!!!!!!); while (true) { byte[] receivedBytes = receivingUdpClientReceive(ref remoteiendpoint); string returnData = EncodingASCIIGetString(receivedBytes); ConsoleWriteLine( + returnDataToString()); } } catch (Exception ex) { ConsoleWriteLine(exToString ()); } } } } 由于是一个聊天程序因此需要打开两个窗口试验时候将A窗口的Local端口号设置为Remote端口号设置为B窗口正好与A端口号相反这样就可以正常运行了! |