日期:2010-04-29  浏览次数:20517 次

使用UDPClient类
这个是我写的测试代码,供参考~

using System;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
using System.Data;
using System.Globalization;
using System.Net;
using System.Net.Sockets;
using System.Threading;
using System.Text;

namespace UDPWinTest
{
/// <summary>
/// Form1 的摘要说明。
/// </summary>
public class Form1 : System.Windows.Forms.Form
{
private System.Windows.Forms.Button btnStart;
private System.Windows.Forms.Button btnJoin;
private System.Windows.Forms.TextBox txtServerIP;
private System.Windows.Forms.Button button1;
private System.Windows.Forms.TextBox txtMsgSend;
private System.Windows.Forms.TextBox txtMessageMain;
/// <summary>
/// 必需的设计器变量。
/// </summary>
private System.ComponentModel.Container components = null;

private static UdpClient m_Client;

private static int ListenerPort = 80;
private static int SenderPort = 80;
private static int LocalPort;
private static int RemotePort;

private static string m_szHostName;

private static IPAddress m_GroupAddress;
private static IPHostEntry m_LocalHost;
private static IPEndPoint m_RemoteEP;
private System.Windows.Forms.Button btnEnd;

private static bool m_Done = false;
private System.Windows.Forms.Button btnClose;

private Thread t = null ;
private Thread t2 = null ;

public Form1()
{
InitializeComponent();
}

/// <summary>
/// 清理所有正在使用的资源。
/// </summary>
protected override void Dispose( bool disposing )
{
if( disposing )
{
if (components != null)
{
components.Dispose();
}
}
base.Dispose( disposing );
}

#region Windows 窗体设计器生成的代码
/// <summary>
/// 设计器支持所需的方法 - 不要使用代码编辑器修改
/// 此方法的内容。
/// </summary>
private void InitializeComponent()
{
this.btnStart = new System.Windows.Forms.Button();
this.btnJoin = new System.Windows.Forms.Button();
this.txtServerIP = new System.Windows.Forms.TextBox();
this.txtMessageMain = new System.Windows.Forms.TextBox();
this.txtMsgSend = new System.Windows.Forms.TextBox();
this.button1 = new System.Windows.Forms.Button();
this.btnEnd = new System.Windows.Forms.Button();
this.btnClose = new System.Windows.Forms.Button();
this.SuspendLayout();
//
// btnStart
//
this.btnStart.Location = new System.Drawing.Point(16, 16);
this.btnStart.Name = "btnStart";
this.btnStart.TabIndex = 0;
this.btnStart.Text = "Start";
this.btnStart.Click += new System.EventHandler(this.btnStart_Click);
//
// btnJoin
//
this.btnJoin.Location = new System.Drawing.Point(408, 16);
this.btnJoin.Name = "btnJoin";
this.btnJoin.TabIndex = 1;
this.btnJoin.Text = "Join";
this.btnJoin.Click += new System.EventHandler(this.btnJoin_Click);
//
// txtServerIP
//
this.txtServerIP.Location = new Syst