熱點推薦:
您现在的位置: 電腦知識網 >> 編程 >> .NET編程 >> 正文

一個基於UDP的聊天應用程序

2022-06-13   來源: .NET編程 

  這些天由於有個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端口號相反這樣就可以正常運行了!


From:http://tw.wingwit.com/Article/program/net/201311/13800.html
    推薦文章
    Copyright © 2005-2022 電腦知識網 Computer Knowledge   All rights reserved.