C# UDP 网络聊天程序

   学习了UDP协议的使用以及TCP协议的对比,各有各的优势!

个人理解优势区别如下:

1:UDP协议称为不可靠的传输协议,因为在从发送方接收方的传递过程中出现的数据丢失,协议本身并不能做出任何检测或者提示。

2:UDP速度比TCP快,因为UDP不需要先与对方建立连接,也不需要连接确认,因此速度要快的多。

理解下使用情景:

并不是说一个程序用UDP就用UDP 用TCP就用TCP,比如说QQ聊天,我们要开视频,语音,发送文件,文字。

其中开视频,语音就可以用UDP协议去做,文字也可以用UDP协议去做。而发送文件就用TCP去做啦,因为发送文件比较大的话 中途数据丢失,造成文件的完整性。。也会导致出问题。。而视频,在线电影这些就无所谓了,丢一点点也是看不出来的。


-------------------------------------------------分割线---------------------------------------


该程序测试了局域网,外网。

下面也说下连接局域网和外网的方式:

局域网:直接在软件上指向目标机的内网IP地址即可(如:192.168.1.223)

外网:指向目标机的外网IP地址,并且本机与目标机的路由器务必映射端口8889(可自行在源码里更改)


以下是截图与完整代码:


截图:


完整代码:


引入命名空间:

using System.Net;
using System.Net.Sockets;
using System.Threading;

代码:

namespace UdpChatExample
{
    public partial class FormChat : Form
    {
        /// <summary>接收用</summary>
        private UdpClient receiveUdpClient;
        /// <summary>发送用</summary>
        private UdpClient sendUdpClient;
        /// <summary>和本机绑定的端口号</summary>
        private const int port = 18001;
        /// <summary>本机IP</summary>
        IPAddress ip;
        /// <summary>远程主机IP</summary>
        IPAddress remoteIp;
        public FormChat()
        {
            InitializeComponent();
            //获取本机可用IP地址
            IPAddress[] ips = Dns.GetHostAddresses(Dns.GetHostName());
            ip = ips[ips.Length - 1];
            //为了在同一台机器调试,此IP也作为默认远程IP
            remoteIp = ip;
            textBoxRemoteIP.Text = remoteIp.ToString();
            textBoxSend.Text = "你好!";
        }
        private void FormChat_Load(object sender, EventArgs e)
        {
            //创建一个线程接收远程主机发来的信息
            Thread myThread = new Thread(ReceiveData);
            //将线程设为后台运行
            myThread.IsBackground = true;
            myThread.Start();
            textBoxSend.Focus();
        }
        private void ReceiveData()
        {
            IPEndPoint local = new IPEndPoint(ip, port);
            receiveUdpClient = new UdpClient(local);
            IPEndPoint remote = new IPEndPoint(IPAddress.Any, 0);
            while (true)
            {
                try
                {
                    //关闭udpClient时此句会产生异常
                    byte[] receiveBytes = receiveUdpClient.Receive(ref remote);
                    string receiveMessage = Encoding.Unicode.GetString(
                        receiveBytes, 0, receiveBytes.Length);
                    AddItem(listBoxReceive, string.Format("来自{0}:{1}", remote, receiveMessage));
                }
                catch
                {
                    break;
                }
            }
        }
        private void buttonSend_Click(object sender, EventArgs e)
        {
            Thread t = new Thread(SendMessage);
            t.IsBackground = true;
            t.Start(textBoxSend.Text);
        }
        /// <summary>发送数据到远程主机</summary>
        private void SendMessage(object obj)
        {
            string message = (string)obj;
            sendUdpClient = new UdpClient(0);
            byte[] bytes = System.Text.Encoding.Unicode.GetBytes(message);
            IPEndPoint iep = new IPEndPoint(remoteIp, port);
            try
            {
                sendUdpClient.Send(bytes, bytes.Length, iep);
                AddItem(listBoxStatus, string.Format("向{0}发送:{1}", iep, message));
                ClearTextBox();
            }
            catch (Exception ex)
            {
                AddItem(listBoxStatus, "发送出错:" + ex.Message);
            }
        }
        delegate void AddListBoxItemDelegate(ListBox listbox, string text);
        private void AddItem(ListBox listbox, string text)
        {
            if (listbox.InvokeRequired)
            {
                AddListBoxItemDelegate d = AddItem;
                listbox.Invoke(d, new object[] { listbox, text });
            }
            else
            {
                listbox.Items.Add(text);
                listbox.SelectedIndex = listbox.Items.Count - 1;
                listbox.ClearSelected();
            }
        }
        delegate void ClearTextBoxDelegate();
        private void ClearTextBox()
        {
            if (textBoxSend.InvokeRequired)
            {
                ClearTextBoxDelegate d = ClearTextBox;
                textBoxSend.Invoke(d);
            }
            else
            {
                textBoxSend.Clear();
                textBoxSend.Focus();
            }
        }
    }
}


如果编译有问题的朋友,可以到下面地址下载我上传的资源文件,谢谢。

下载地址: http://download.csdn.net/source/3504525

评论 35
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Andrew_wx

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值