1)求UDP发送和接收数据的代码
2)客户端怎么向服务器端请求

解决方案 »

  1.   

    为什么不去看一下MSDN,学会用并不是那么复杂.
    从Socket入手
    以下是MSDN的一些代码:
    UdpClient udpClient = new UdpClient();
        try{
             udpClient.Connect("www.contoso.com", 11000);         // Sends a message to the host to which you have connected.
             Byte[] sendBytes = Encoding.ASCII.GetBytes("Is anybody there?");
          
             udpClient.Send(sendBytes, sendBytes.Length);         // Sends a message to a different host using optional hostname and port parameters.
             UdpClient udpClientB = new UdpClient();
             udpClientB.Send(sendBytes, sendBytes.Length, "AlternateHostMachineName", 11000);         //IPEndPoint object will allow us to read datagrams sent from any source.
             IPEndPoint RemoteIpEndPoint = new IPEndPoint(IPAddress.Any, 0);         // Blocks until a message returns on this socket from a remote host.
             Byte[] receiveBytes = udpClient.Receive(ref RemoteIpEndPoint); 
             string returnData = Encoding.ASCII.GetString(receiveBytes);
       
             // Uses the IPEndPoint object to determine which of these two hosts responded.
             Console.WriteLine("This is the message you received " +
                                          returnData.ToString());
             Console.WriteLine("This message was sent from " +
                                         RemoteIpEndPoint.Address.ToString() +
                                         " on their port number " +
                                         RemoteIpEndPoint.Port.ToString());          udpClient.Close();
              udpClientB.Close();
              
              }  
           catch (Exception e ) {
                      Console.WriteLine(e.ToString());
            }
      

  2.   

    送你一个刚做的
    server端:
    using System;
    using System.Drawing;
    using System.Collections;
    using System.ComponentModel;
    using System.Windows.Forms;
    using System.Data;namespace Serverchat
    {
    /// <summary>
    /// Form1 的摘要说明。
    /// </summary>
    public class Form1 : System.Windows.Forms.Form
    {
    private System.Windows.Forms.RichTextBox rTBReceive;
    private System.Windows.Forms.RichTextBox rTBSend;
    private System.Windows.Forms.TextBox tbRemoteIp;
    private System.Windows.Forms.TextBox tbRemotePort;
    private System.Windows.Forms.TextBox tbPort;
    private System.Windows.Forms.Label lbport;
    private System.Windows.Forms.Label label1;
    private System.Windows.Forms.Label label2;
    private System.Windows.Forms.Button button1;
    private Server _server=null;
    private System.Windows.Forms.Button button2;
    private System.Windows.Forms.Button button3;
    private System.Windows.Forms.Button button4;
    /// <summary>
    /// 必需的设计器变量。
    /// </summary>
    private System.ComponentModel.Container components = null; public Form1()
    {
    //
    // Windows 窗体设计器支持所必需的
    //
    InitializeComponent(); //
    // TODO: 在 InitializeComponent 调用后添加任何构造函数代码
    //
    } /// <summary>
    /// 清理所有正在使用的资源。
    /// </summary>
    protected override void Dispose( bool disposing )
    {
    try
    {
    if (this._server != null)
    _server.Stop();
    }
    catch
    {
    }
    if( disposing )
    {
    if (components != null) 
    {
    components.Dispose();
    }
    }
    base.Dispose( disposing );
    } #region Windows 窗体设计器生成的代码
    /// <summary>
    /// 设计器支持所需的方法 - 不要使用代码编辑器修改
    /// 此方法的内容。
    /// </summary>
    private void InitializeComponent()
    {
    this.rTBReceive = new System.Windows.Forms.RichTextBox();
    this.rTBSend = new System.Windows.Forms.RichTextBox();
    this.tbRemoteIp = new System.Windows.Forms.TextBox();
    this.tbRemotePort = new System.Windows.Forms.TextBox();
    this.tbPort = new System.Windows.Forms.TextBox();
    this.lbport = new System.Windows.Forms.Label();
    this.label1 = new System.Windows.Forms.Label();
    this.label2 = new System.Windows.Forms.Label();
    this.button1 = new System.Windows.Forms.Button();
    this.button2 = new System.Windows.Forms.Button();
    this.button3 = new System.Windows.Forms.Button();
    this.button4 = new System.Windows.Forms.Button();
    this.SuspendLayout();
    // 
    // rTBReceive
    // 
    this.rTBReceive.BackColor = System.Drawing.Color.FromArgb(((System.Byte)(128)), ((System.Byte)(128)), ((System.Byte)(255)));
    this.rTBReceive.ForeColor = System.Drawing.Color.Brown;
    this.rTBReceive.Location = new System.Drawing.Point(144, 16);
    this.rTBReceive.Name = "rTBReceive";
    this.rTBReceive.Size = new System.Drawing.Size(480, 208);
    this.rTBReceive.TabIndex = 8;
    this.rTBReceive.Text = "";
    // 
    // rTBSend
    // 
    this.rTBSend.BackColor = System.Drawing.Color.FromArgb(((System.Byte)(128)), ((System.Byte)(128)), ((System.Byte)(255)));
    this.rTBSend.ForeColor = System.Drawing.Color.Brown;
    this.rTBSend.Location = new System.Drawing.Point(144, 288);
    this.rTBSend.Name = "rTBSend";
    this.rTBSend.Size = new System.Drawing.Size(480, 56);
    this.rTBSend.TabIndex = 9;
    this.rTBSend.Text = "";
    // 
    // tbRemoteIp
    // 
    this.tbRemoteIp.Location = new System.Drawing.Point(200, 248);
    this.tbRemoteIp.Name = "tbRemoteIp";
    this.tbRemoteIp.Size = new System.Drawing.Size(120, 21);
    this.tbRemoteIp.TabIndex = 10;
    this.tbRemoteIp.Text = "";
    // 
    // tbRemotePort
    // 
    this.tbRemotePort.Location = new System.Drawing.Point(440, 248);
    this.tbRemotePort.Name = "tbRemotePort";
    this.tbRemotePort.Size = new System.Drawing.Size(120, 21);
    this.tbRemotePort.TabIndex = 11;
    this.tbRemotePort.Text = "";
    // 
    // tbPort
    // 
    this.tbPort.Location = new System.Drawing.Point(16, 48);
    this.tbPort.Name = "tbPort";
    this.tbPort.Size = new System.Drawing.Size(120, 21);
    this.tbPort.TabIndex = 12;
    this.tbPort.Text = "";
    // 
    // lbport
    // 
    this.lbport.Location = new System.Drawing.Point(40, 16);
    this.lbport.Name = "lbport";
    this.lbport.TabIndex = 13;
    this.lbport.Text = "监听端口";
    // 
    // label1
    // 
    this.label1.Location = new System.Drawing.Point(112, 248);
    this.label1.Name = "label1";
    this.label1.Size = new System.Drawing.Size(88, 23);
    this.label1.TabIndex = 14;
    this.label1.Text = "连接远程主机";
    // 
    // label2
    // 
    this.label2.Location = new System.Drawing.Point(368, 248);
    this.label2.Name = "label2";
    this.label2.Size = new System.Drawing.Size(64, 23);
    this.label2.TabIndex = 15;
    this.label2.Text = "连接端口";
    // 
    // button1
    // 
    this.button1.Location = new System.Drawing.Point(72, 392);
    this.button1.Name = "button1";
    this.button1.TabIndex = 16;
    this.button1.Text = "开始监听";
    this.button1.Click += new System.EventHandler(this.button1_Click);
    // 
    // button2
    // 
    this.button2.Location = new System.Drawing.Point(208, 392);
    this.button2.Name = "button2";
    this.button2.TabIndex = 17;
    this.button2.Text = "停止监听";
    this.button2.Click += new System.EventHandler(this.button2_Click);
    // 
    // button3
    // 
    this.button3.Location = new System.Drawing.Point(352, 392);
    this.button3.Name = "button3";
    this.button3.TabIndex = 18;
    this.button3.Text = "发送消息";
    this.button3.Click += new System.EventHandler(this.button3_Click);
    // 
    // button4
    // 
    this.button4.Location = new System.Drawing.Point(488, 392);
    this.button4.Name = "button4";
    this.button4.TabIndex = 19;
    this.button4.Text = "退出";
    this.button4.Click += new System.EventHandler(this.button4_Click);
    // 
    // Form1
    // 
    this.AutoScaleBaseSize = new System.Drawing.Size(6, 14);
    this.ClientSize = new System.Drawing.Size(648, 477);
    this.Controls.Add(this.button4);
    this.Controls.Add(this.button3);
    this.Controls.Add(this.button2);
    this.Controls.Add(this.button1);
    this.Controls.Add(this.label2);
    this.Controls.Add(this.label1);
    this.Controls.Add(this.lbport);
    this.Controls.Add(this.tbPort);
    this.Controls.Add(this.tbRemotePort);
    this.Controls.Add(this.tbRemoteIp);
    this.Controls.Add(this.rTBSend);
    this.Controls.Add(this.rTBReceive);
    this.Name = "Form1";
    this.Text = "Form1";
    this.ResumeLayout(false); }
    #endregion /// <summary>
    /// 应用程序的主入口点。
    /// </summary>
    [STAThread]
    static void Main() 
    {
    Application.Run(new Form1());
    } private void button1_Click(object sender, System.EventArgs e)
    {
    if ( this.tbPort.Text.Length > 0) 
    {
    _server = new Server(this,Int32.Parse(this.tbPort.Text));
    _server.Start();
    }
    } private void button2_Click(object sender, System.EventArgs e)
    {
    if  ( _server != null)
    _server.Stop();
    } private void button3_Click(object sender, System.EventArgs e)
    {
    if ( _server != null)
    _server.Send();
    } private void button4_Click(object sender, System.EventArgs e)
    {
    this.Close();
    } public String MessageTxt
    {
    set { rTBReceive.AppendText(value);}
    }
    public String SendMessageTxt
    {
    get { return this.rTBSend.Text;}
    } public String RemoteIp
    {
    set { this.tbRemoteIp.Text = value ;}
    }
    public String RemotePort
    {
    set { this.tbRemotePort.Text = value ;}
    }
    }
    }
      

  3.   

    server类:using System;
    using System.Net.Sockets;
    using System.Net;
    using System.Threading;
    using System.Text;
    namespace Serverchat
    {
    /// <summary> 
    /// Server 的摘要说明。 
    /// </summary> 
    public class Server 

    private UdpClient _server; 
    // private UserCollection userList; 
    private Thread serverThread; 
    private IPEndPoint remotePoint;
    private int _port ;
    private IPEndPoint _userEndPoint = null ;
    private Form1 _frm;
    public Server( Form1 frm,int port) 

    // userList = new UserCollection(); 
    this._frm = frm;
    this._port = port; 
    remotePoint = new IPEndPoint(IPAddress.Any, 0); 
    serverThread = new Thread(new ThreadStart(Run)); 

    public void Start() 

    try 

    _server = new UdpClient(_port); 
    serverThread.Start(); 
    // Console.WriteLine("P2P Server started, waiting client connect..."); 

    catch(Exception exp) 

    // Console.WriteLine("Start P2P Server error: " + exp.Message); 
    throw exp; 


    public void Stop() 

    try

    if(serverThread != null) serverThread.Abort(); 
    if(_server != null) _server.Close(); 

    catch(Exception exp) 

    throw exp; 


    private void Run() 

    // byte[] buffer = null; 
    while (true) 

    byte[] msgBuffer = _server.Receive(ref remotePoint); 
    try 
    {
    ASCIIEncoding encode = new ASCIIEncoding();
    string RecMessage = encode.GetString(msgBuffer);
    _frm.MessageTxt = RecMessage;
    _userEndPoint = new IPEndPoint(remotePoint.Address, remotePoint.Port); 
    _frm.RemoteIp = remotePoint.Address.ToString();
    _frm.RemotePort = remotePoint.Port.ToString(); /* string send=_frm.SendMessageTxt+"\r\n";
    // System.Text.ASCIIEncoding encode = new ASCIIEncoding();
    buffer = encode.GetBytes(send);
    _server.Send(buffer, buffer.Length, remotePoint); 
    */
    Thread.Sleep(500); 

    catch{} 

    }  public void Send()
    {
    if ( _userEndPoint != null && _server != null)
    {
    byte[] buffer = null; 
    ASCIIEncoding encode = new ASCIIEncoding();
    string send=_frm.SendMessageTxt+"\r\n";
    buffer = encode.GetBytes(send);
    _server.Send(buffer, buffer.Length, _userEndPoint); 
    }
    }
    }}
      

  4.   

    客户端:
    using System;
    using System.Drawing;
    using System.Collections;
    using System.ComponentModel;
    using System.Windows.Forms;
    using System.Data;
    using System.Net;
    using System.Net.Sockets;
    using System.Text;
    using System.Threading;
    namespace ClientChat
    {
    /// <summary>
    /// Form1 的摘要说明。
    /// </summary>
    public class Form1 : System.Windows.Forms.Form
    {
    private System.Windows.Forms.Button button1;
    private System.Windows.Forms.Label label1;
    private System.Windows.Forms.Label label2;
    private System.Windows.Forms.Label label4;
    private System.Windows.Forms.Label label3;
    private System.Windows.Forms.RichTextBox rTBSend;
    private System.Windows.Forms.RichTextBox rTBReceive;
    private IPAddress myIp=IPAddress.Parse("127.0.0.1");
    private IPEndPoint MyServer;
    private UdpClient client;
    private IPEndPoint _receivePoint ;
    private System.Windows.Forms.TextBox tBIp;
    private System.Windows.Forms.TextBox tBPort;
    private System.Windows.Forms.Button button2;
    private bool _listen = false;
    private System.Windows.Forms.Button button3;
    private Thread clientThread = null;
    private System.Windows.Forms.Button button4;
    /// <summary>
    /// 必需的设计器变量。
    /// </summary>
    private System.ComponentModel.Container components = null; public Form1()
    {
    //
    // Windows 窗体设计器支持所必需的
    //
    InitializeComponent(); //
    // TODO: 在 InitializeComponent 调用后添加任何构造函数代码
    //
    } /// <summary>
    /// 清理所有正在使用的资源。
    /// </summary>
    protected override void Dispose( bool disposing )
    {
    if (this.clientThread != null) this.clientThread.Abort();
    if (client !=null) client.Close();
    if( disposing )
    {
    if (components != null) 
    {
    components.Dispose();
    }
    }
    base.Dispose( disposing );
    } #region Windows 窗体设计器生成的代码
    /// <summary>
    /// 设计器支持所需的方法 - 不要使用代码编辑器修改
    /// 此方法的内容。
    /// </summary>
    private void InitializeComponent()
    {
    this.button1 = new System.Windows.Forms.Button();
    this.label1 = new System.Windows.Forms.Label();
    this.tBIp = new System.Windows.Forms.TextBox();
    this.tBPort = new System.Windows.Forms.TextBox();
    this.label2 = new System.Windows.Forms.Label();
    this.label4 = new System.Windows.Forms.Label();
    this.label3 = new System.Windows.Forms.Label();
    this.rTBSend = new System.Windows.Forms.RichTextBox();
    this.rTBReceive = new System.Windows.Forms.RichTextBox();
    this.button2 = new System.Windows.Forms.Button();
    this.button3 = new System.Windows.Forms.Button();
    this.button4 = new System.Windows.Forms.Button();
    this.SuspendLayout();
    // 
    // button1
    // 
    this.button1.Location = new System.Drawing.Point(216, 272);
    this.button1.Name = "button1";
    this.button1.TabIndex = 0;
    this.button1.Text = "发送消息";
    this.button1.Click += new System.EventHandler(this.button1_Click);
    // 
    // label1
    // 
    this.label1.Location = new System.Drawing.Point(32, 232);
    this.label1.Name = "label1";
    this.label1.Size = new System.Drawing.Size(56, 23);
    this.label1.TabIndex = 1;
    this.label1.Text = "服务器IP";
    // 
    // tBIp
    // 
    this.tBIp.Location = new System.Drawing.Point(88, 232);
    this.tBIp.Name = "tBIp";
    this.tBIp.TabIndex = 2;
    this.tBIp.Text = "";
    // 
    // tBPort
    // 
    this.tBPort.Location = new System.Drawing.Point(312, 232);
    this.tBPort.Name = "tBPort";
    this.tBPort.TabIndex = 4;
    this.tBPort.Text = "";
    // 
    // label2
    // 
    this.label2.Location = new System.Drawing.Point(256, 232);
    this.label2.Name = "label2";
    this.label2.Size = new System.Drawing.Size(56, 23);
    this.label2.TabIndex = 3;
    this.label2.Text = "请求端口";
    // 
    // label4
    // 
    this.label4.Location = new System.Drawing.Point(8, 112);
    this.label4.Name = "label4";
    this.label4.Size = new System.Drawing.Size(72, 16);
    this.label4.TabIndex = 22;
    this.label4.Text = "发送消息:";
    // 
    // label3
    // 
    this.label3.Location = new System.Drawing.Point(8, 8);
    this.label3.Name = "label3";
    this.label3.Size = new System.Drawing.Size(72, 16);
    this.label3.TabIndex = 21;
    this.label3.Text = "接收信息:";
    // 
    // rTBSend
    // 
    this.rTBSend.Location = new System.Drawing.Point(88, 112);
    this.rTBSend.Name = "rTBSend";
    this.rTBSend.Size = new System.Drawing.Size(480, 96);
    this.rTBSend.TabIndex = 24;
    this.rTBSend.Text = "";
    // 
    // rTBReceive
    // 
    this.rTBReceive.Location = new System.Drawing.Point(88, 8);
    this.rTBReceive.Name = "rTBReceive";
    this.rTBReceive.Size = new System.Drawing.Size(480, 96);
    this.rTBReceive.TabIndex = 23;
    this.rTBReceive.Text = "";
    // 
    // button2
    // 
    this.button2.Location = new System.Drawing.Point(80, 272);
    this.button2.Name = "button2";
    this.button2.TabIndex = 25;
    this.button2.Text = "消息设置";
    this.button2.Click += new System.EventHandler(this.button2_Click);
    // 
    // button3
    // 
    this.button3.Location = new System.Drawing.Point(328, 272);
    this.button3.Name = "button3";
    this.button3.TabIndex = 26;
    this.button3.Text = "停止发送";
    this.button3.Click += new System.EventHandler(this.button3_Click);
    // 
    // button4
    // 
    this.button4.Location = new System.Drawing.Point(440, 272);
    this.button4.Name = "button4";
    this.button4.TabIndex = 27;
    this.button4.Text = "关闭";
    this.button4.Click += new System.EventHandler(this.button4_Click);
    // 
    // Form1
    // 
    this.AutoScaleBaseSize = new System.Drawing.Size(6, 14);
    this.ClientSize = new System.Drawing.Size(600, 341);
    this.Controls.Add(this.button4);
    this.Controls.Add(this.button3);
    this.Controls.Add(this.button2);
    this.Controls.Add(this.label4);
    this.Controls.Add(this.label3);
    this.Controls.Add(this.rTBSend);
    this.Controls.Add(this.rTBReceive);
    this.Controls.Add(this.tBPort);
    this.Controls.Add(this.label2);
    this.Controls.Add(this.tBIp);
    this.Controls.Add(this.label1);
    this.Controls.Add(this.button1);
    this.Name = "Form1";
    this.Text = "Form1";
    this.ResumeLayout(false); }
    #endregion /// <summary>
    /// 应用程序的主入口点。
    /// </summary>
    [STAThread]
    static void Main() 
    {
    Application.Run(new Form1());
    } private void button1_Click(object sender, System.EventArgs e)
    {
    if ( client == null) 
    {
    MessageBox.Show("请先设置消息通道!","信息栏");
    return;
    }
    _listen = true;
    Byte[] sendbyte=new Byte[64];
    string send=rTBSend.Text+"\r\n";
    System.Text.ASCIIEncoding encode = new ASCIIEncoding();
    sendbyte = encode.GetBytes(send);
    // sendbyte=System.Text.Encoding.BigEndianUnicode.GetBytes(send.ToCharArray());
    client.Send(sendbyte,sendbyte.Length,MyServer);

    _listen = false;
    // clientThread.Start();
    /*byte[] recData1 = client.Receive ( ref _receivePoint ) ;
    string timeString  = timeString = encode.GetString ( recData1 ) ;
    this.rTBReceive.AppendText(timeString);
    client.Close ( ) ;
    */
    } private void button2_Click(object sender, System.EventArgs e)
    {
    myIp=IPAddress.Parse(tBIp.Text);
    MyServer = new IPEndPoint(myIp,Int32.Parse(tBPort.Text));
    client = new UdpClient(Int32.Parse(this.tBPort.Text));
    clientThread=new Thread(new ThreadStart(receive));
    clientThread.IsBackground = true;
    // this.check = false;
    clientThread.Start();
    }