知识大全 一个基于UDP的聊天应用程序

Posted

篇首语:只要还有什么东西不知道,就永远应当学习。本文由小常识网(cha138.com)小编为大家整理,主要介绍了知识大全 一个基于UDP的聊天应用程序相关的知识,希望对你有一定的参考价值。

一个基于UDP的聊天应用程序  以下文字资料是由(全榜网网www.cha138.com)小编为大家搜集整理后发布的内容,让我们赶快一起来看一下吧!

  这些天由于有个p p的项目 于是恶补了一下自己在网络编程方面的知识 下面一个程序是我在这过程中的一个很小的程序 想看看这个udp协议是不是适合做p p 如果哪位朋友是做p p的 请不吝赐教!

  下面将我自己的代码贴出来 希望各位指正!

  using System;

  using System Collections Generic;

  using System Text;

  using System Net;

  using System Net Sockets;

  using System Threading;

  namespace UDPChat

  

  class Program

  

  private static IPAddress remoteAddress;

  private static int remotePort;

  private static int localPort;

  [STAThread ]

  static void Main(string[] args)

  

  try

  

  Console Write( Enter Local Port );

  localPort = Convert ToInt (Console ReadLine());

  Console Write( Enter Remote Port );

  remotePort = Convert ToInt (Console ReadLine());

  Console Write( Enter Remote IP address );

  remoteAddress = IPAddress Parse(Console ReadLine());

  Thread tRec = new Thread(new ThreadStart(Receiver));

  tRec Start();

  while (true)

  

  Send(Console ReadLine());

  

  

  catch (Exception ex)

  

  Console WriteLine(ex ToString ());

  

  

  private static void Send(string p)

  

  UdpClient sender = new UdpClient();

  IPEndPoint endPoint = new IPEndPoint(remoteAddress remotePort );

  try

  

  byte[] bytes = Encoding ASCII GetBytes(p);

  sender Send(bytes bytes Length endPoint);

  

  catch (Exception ex)

  

  Console WriteLine(ex ToString());

  

  finally

  

  sender Close();

  

  

  public static void Receiver()

  

  UdpClient receivingUdpClient = new UdpClient(localPort);

  IPEndPoint remoteiendpoint = null;

  try

  

  Console WriteLine( Ready For Chat!!!!!!!! );

  while (true)

  

  byte[] receivedBytes = receivingUdpClient Receive(ref remoteiendpoint);

  string returnData = Encoding ASCII GetString(receivedBytes);

  Console WriteLine( + returnData ToString());

  

  

  catch (Exception ex)

  

  Console WriteLine(ex ToString ());

  

  

  

  

cha138/Article/program/net/201311/13800

相关参考