作者:宝宝贝贝侠 | 来源:互联网 | 2023-09-05 17:47
UDP聊天代码监听服务器端代码添加引用usingSystem;usingSystem.Drawing;usingSystem.Collections;usingSystem.Co
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;
///
/// udp连接系统定义的必需的设计器变量
///
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="监听结束...";
}