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

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="监听结束...";
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值