您的位置:首页 > 其它

Udp通讯实例

2010-04-27 15:01 225 查看
代码

namespace MyUdpClient
{
public partial class FrmUdpClient : Form
{
private Thread thread1;
private UdpClient udpSend;
private UdpClient udpReceive;

public FrmUdpClient()
{
InitializeComponent();
}

private void FrmUdpClient_Load(object sender, EventArgs e)
{
thread1 = new Thread(new ThreadStart(ReceiveMessage));
thread1.Start();
}

private void ReceiveMessage()
{
byte[] bytes = null;
//在本机制定和的端口连接
udpReceive = new UdpClient(8001);
//将套接字加入广播组
udpReceive.JoinMulticastGroup(IPAddress.Parse("224.100.0.10"), 50);
//接收从远程发送来的消息
IPEndPoint iep = new IPEndPoint(IPAddress.Any, 0);
while (true)
{
//ref表示引用类型的IPPoint实例接受消息
try
{
bytes = udpReceive.Receive(ref iep);
}
catch (Exception ex)
{
MessageBox.Show("接收消息错误!");
return;
}
finally
{
}
string str = Encoding.UTF8.GetString(bytes, 0, bytes.Length);
if (str == "")
{
MessageBox.Show("接收消息错误!");
return;
}

string msg = "来自" + iep.ToString() + "的消息";
//显示消息并以message 为消息的标题
DialogResult result = MessageBox.Show(str, msg);
}
}

private void FrmUdpClient_FormClosed(object sender, FormClosedEventArgs e)
{
if (udpSend != null)
{
udpSend.Close();
}
udpReceive.Close();
thread1.Abort();
}

private void btnSend_Click(object sender, EventArgs e)
{
byte[] bytes = null;
//如果发送消息为空,则不发送
if (tbxMessage.Text == "")
{
MessageBox.Show("消息不能为空");
return;
}
//初始化UdpClient
udpSend = new UdpClient();
//实际使用时应将127.0.0.1改为服务器的远程IP
IPAddress remoteIPAddress = IPAddress.Parse("127.0.0.1");
IPEndPoint remoteIPEndPoint = new IPEndPoint(remoteIPAddress, 8002);

bytes = System.Text.Encoding.UTF8.GetBytes(tbxMessage.Text);
//设置重发次数
int retry = 0;
//进入发送消息循环
while (true)
{
//将发送内容转换为字节数组
try
{
udpSend.Send(bytes, bytes.Length, remoteIPEndPoint);
//若成功则退出循环
break;

}
catch (Exception ex)
{
if (retry < 3)
{
//重试次数加1,继续尝试发送
retry++;
continue;
}
else
{
//如果重试次数大于3次,提示发送失败并跳出循环
DialogResult result = MessageBox.Show("发送失败!" + ex.ToString());
break;
}
}
finally
{
}

}

//清空TbxMessage中的内容
tbxMessage.Clear();
//光标还原
tbxMessage.Focus();
udpSend.Close();

}

}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: