Chinaunix首页 | 论坛 | 博客
  • 博客访问: 151893
  • 博文数量: 34
  • 博客积分: 2010
  • 博客等级: 大尉
  • 技术积分: 346
  • 用 户 组: 普通用户
  • 注册时间: 2008-12-19 09:53
文章分类

全部博文(34)

文章存档

2011年(1)

2009年(33)

我的朋友

分类:

2009-06-12 15:10:20

UDP原理就不多说了,网上能搜出一大堆。程序分为客户端和服务器端。实现的功能:服务器端接收客户端发来的数据并显示。

    1.客户端

    界面如下

   

    各控件名称:textBoxIP,textBoxPort,textBoxTxt,buttonSend。

    客户端程序通过服务器的IP地址和端口号向服务器发送数据,IP地址默认为localhost,也可以是127.0.0.1 。

    客户端程序代码:

using System;
using System.Text;
using System.Windows.Forms;
using System.Net.Sockets;
using System.Net;

namespace UDPClient
{
    public partial class Form1 : Form
    {
        UdpClient uc;
        public Form1()
        {
            InitializeComponent();
            uc = new UdpClient();
            this.textBoxIP.Text = "localhost";
        }

        private void buttonSend_Click(object sender, EventArgs e)
        {
            string host = this.textBoxIP.Text;
            int port = Convert.ToInt32(this.textBoxPort.Text);
            string txt = this.textBoxTxt.Text;
            byte[] b = System.Text.Encoding.UTF8.GetBytes(txt);
            if (host == "localhost")
            {
                host = Dns.GetHostName();
            }
            if (uc!=null)
            {
                uc.Send(b, b.Length, host, port);
            }
        }
    }
}

 

    2.服务器端界面

   

    各控件名称:textBoxPort,listBox1,buttonStart

    服务器端设定接收数据的端口,点击start开始。端口改变要重新start。

    代码如下:

using System;
using System.Text;
using System.Windows.Forms;
using System.Net.Sockets;
using System.Net;
using System.Threading;

namespace UDPServer
{
    public partial class Form1 : Form
    {
        UdpClient uc = null;
        Thread th = null;
        public Form1()
        {
            InitializeComponent();

            //屏蔽跨线程改控件属性那个异常
            CheckForIllegalCrossThreadCalls = false;
        }

        private void listen()
        {

            //声明终结点,IP,端口号随便指定
            IPEndPoint iep = new IPEndPoint(IPAddress.Parse("192.168.0.147"), 8888);
            while (true)
            {

                //获得Form1发送过来的数据包
                string text = System.Text.Encoding.UTF8.GetString(uc.Receive(ref iep));

                //加入ListBox
                this.listBox1.Items.Add(text);
            }
        }

        private void button1_Click(object sender, EventArgs e)
        {
            //注意此处端口号要与发送方相同
            int port = Convert.ToInt32(this.textBoxPort.Text);
            uc = new UdpClient(port);

            //实例化线程
            th = new Thread(new ThreadStart(listen));

            //设置为后台
            th.IsBackground = true;
            th.Start();
        }

        private void textBoxPort_TextChanged(object sender, EventArgs e)
        {
            //端口改变则需要重新启动线程
            if (th!=null)
            {
                th.Abort();
            }
        }
    }
}

阅读(1166) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~