搜索: 标题内容作者  
  首页C#教程C#实例
背景:
阅读新闻

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

[日期:2009-03-16]   来源:互联网整理  作者:佚名   [字体: ]
    新闻简介: 这些天由于有个p2p的项目,于是恶补了一下自己在网络编程方面的知识,下面一个程序是我在这过程中的一个很小的程序,想看看这个udp协议是不是适合做p2p。如果哪位朋友是做p2p的,请不吝赐教!加小弟的QQ:422158979,小弟先谢谢了!
        关 键 词:  
这些天由于有个p2p的项目,于是恶补了一下自己在网络编程方面的知识,下面一个程序是我在这过程中的一个很小的程序,想看看这个udp协议是不是适合做p2p。如果哪位朋友是做p2p的,请不吝赐教!加小弟的QQ:422158979,小弟先谢谢了!

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



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.ToInt16(Console.ReadLine());

Console.Write("Enter Remote Port----");
remotePort = Convert.ToInt16(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 ());
}
}
}
}
由于是一个聊天程序,因此需要打开两个窗口。试验时候将A窗口的Local端口号设置为2002,Remote端口号设置为2001。B窗口正好与A端口号相反。这样就可以正常运行了!

If you believe an article violates your rights or the rights of others, please contact us.

收藏 推荐 打印 | 录入:admin | 阅读:
相关新闻      
友情链接
本文评论   [发表评论] 全部评论 (0)
赞助商广告
热门评论