A股上市公司传智教育(股票代码 003032)旗下技术交流社区北京昌平校区

 找回密码
 加入黑马

QQ登录

只需一步,快速开始

© lilong9298 中级黑马   /  2013-6-18 15:49  /  846 人查看  /  1 人回复  /   0 人收藏 转载请遵从CC协议 禁止商业使用本文

怎样使用udp协议来实现客户端与服务器的访问,有高手知道吗

评分

参与人数 1技术分 +1 收起 理由
苏波 + 1

查看全部评分

1 个回复

倒序浏览
  1. using System;
  2. using System.Collections.Generic;
  3. using System.ComponentModel;
  4. using System.Data;
  5. using System.Drawing;
  6. using System.Text;
  7. using System.Windows.Forms;
  8. using System.Net;
  9. using System.Net.Sockets;
  10. using System.Threading;

  11. namespace test_udp
  12. {
  13.     public partial class Form1 : Form
  14.     {
  15.         UdpClient udpclient;
  16.         Byte[] sendBytes;
  17.         IPEndPoint temp;
  18.         public Form1()
  19.         {
  20.             InitializeComponent();
  21.         }

  22.         //发送按键
  23.         private void button1_Click(object sender, EventArgs e)
  24.         {
  25.             //定义一个字节数组,用来存放发送到远程主机的信息
  26.             sendBytes = Encoding.Default.GetBytes(textBox3.Text);
  27.             //调用send方法发送到远程主机
  28.             udpclient.Send(sendBytes, sendBytes.Length);
  29.         }

  30.         //确认配置
  31.         private void button2_Click(object sender, EventArgs e)
  32.         {
  33.             //实例化udpclient对象
  34.             udpclient = new UdpClient(Convert.ToInt32(textBox2.Text));
  35.             //调用connect建立默认远程主机
  36.             udpclient.Connect(textBox1.Text, Convert.ToInt32(textBox2.Text));
  37.             //实例化ipendpoint对象,用来显示响应主机的标识
  38.             temp = new IPEndPoint(IPAddress.Any,0);
  39.             //开启接收线程
  40.             Thread recv_udp = new Thread(new ThreadStart(recv_udp_func));
  41.             recv_udp.Start();
  42.         }

  43.         //接收线程
  44.         public void recv_udp_func()
  45.         {
  46.             while (true)
  47.             {
  48.                 //接收数据包
  49.                 Byte[] recv_bytes = udpclient.Receive(ref temp);
  50.                 //将得到的数据包转换为字符串形式
  51.                 string return_data = Encoding.Default.GetString(recv_bytes,0,recv_bytes.Length);
  52.                 //显示
  53.                 this.Invoke((EventHandler)delegate { this.textBox4.Text = return_data; });
  54.             }
  55.         }
  56.     }
  57. }
复制代码

评分

参与人数 1技术分 +1 收起 理由
苏波 + 1

查看全部评分

回复 使用道具 举报
您需要登录后才可以回帖 登录 | 加入黑马