UDP聊天代码监听服务器端代码

来源:互联网 发布:软件著作权证书有效期 编辑:程序博客网 时间:2024/06/14 11:01

UDP聊天代码监听服务器端代码

添加引用

using System;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;

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

 

/// <summary>
  /// udp连接系统定义的必需的设计器变量
  /// </summary>
  public UdpClient udpClient;
  private System.Windows.Forms.TextBox textBox4;
  private System.Windows.Forms.Label label4;
  private System.Windows.Forms.TextBox textBox3;
  private System.Windows.Forms.Label label3;
  public Thread UdpThread;
  public const int listenPort = 12000;

按钮事件(监听消息)

private void button2_Click(object sender, System.EventArgs e)
  {
   
   if (udpClient!=null)
   {
    UdpThread.Abort();
    Thread.Sleep(TimeSpan.FromMilliseconds(500));
    udpClient.Close();
   }
   try
   { 
    udpClient=new UdpClient(int.Parse(textBox2.Text));
    UdpThread=new Thread(new ThreadStart(UdpReciveThread));
    UdpThread.Start();

   }
   catch(Exception y)
   {
    MessageBox.Show(this,y.Message,"Error",MessageBoxButtons.OK,MessageBoxIcon.Error);
   }
   
  } 

//接收数据线程
  public void UdpReciveThread()
  {
   
   bool done = false;

   
      
   IPEndPoint remoteHost=new IPEndPoint(IPAddress.Any,listenPort);

   this.statusBar1.Text="正在启动监听...";
   while(udpClient!=null && Thread.CurrentThread.ThreadState.Equals(ThreadState.Running))
   {
    try
    {
     this.statusBar1.Text="等待连接...";
     byte[] buf=udpClient.Receive(ref remoteHost);
     string bufs=Encoding.UTF8.GetString(buf);


     int ListCount=0;
     if(listView1.Items.Count==0)
     {
      listView1.Items.Add(DateTime.Now.ToString());
      listView1.Items[0].SubItems.Add(remoteHost.Address.ToString());
      listView1.Items[0].SubItems.Add(bufs);
     }
     else
     {
      ListCount=listView1.Items.Count;
      listView1.Items.Add(DateTime.Now.ToString());
      listView1.Items[ListCount].SubItems.Add(remoteHost.Address.ToString());
      listView1.Items[ListCount].SubItems.Add(bufs);
    
     }
     this.statusBar1.Text="数据报长度:"+bufs.Length;
     
     
    }
    catch(Exception y)
    {
     this.statusBar1.Text="发生错误:"+y.Message+" "+y.Source;

    }

   }
   this.statusBar1.Text="监听结束...";
  }

 

原创粉丝点击