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

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值