电脑故障

位置:IT落伍者 >> 电脑故障 >> 浏览文章

一个基于UDP的聊天应用程序


发布日期:2018/8/6
 

这些天由于有个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端口号相反这样就可以正常运行了!

上一篇:用VB实现拖放功能

下一篇:简单的实例理解接口的伟大意义