C# UDP接收和发送
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Da
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.NET;
using System.Net.Sockets;
using System.Threading;
namespace WpfTest
{
/// <summary>
/// Window1.xaml 的交互逻辑
/// </summary>
public partial class Window1 : Window
{
public Window1()
{
InitializeComponent();
Thread thread1 = new Thread(new ThreadStart(ReceiveData));
thread1.Start();
}
delegate void TextBoxCallback(string str);
public void SetTextBox(string str)
{
textBox1.Text = str;
}
private int port = 62001;
private UdpClient udpClient;
private void ReceiveData()
{
//在本机指定的端口接收
udpClient = new UdpClient(port);
IPEndPoint remote = null;
//接收从远程主机发送过来的信息;
while (true)
{
try
{
//关闭udpClient时此句会产生异常
byte[] bytes = udpClient.Receive(ref remote);
string str = Encoding.UTF8.GetString(bytes, 0, bytes.Length);
TextBoxCallback tx = SetTextBox;
this.Dispatcher.Invoke(tx, str);
}
catch
{
//退出循环,结束线程
break;
}
finally
{
udpClient.Close();
}
}
}
private void sendData()
{
UdpClient myUdpClient = new UdpClient();
IPAddress remoteIP;
if (IPAddress.TryParse(textBoxRemoteIP.Text, out remoteIP) == false)
{
MessageBox.Show("远程IP格式不正确");
return;
}
IPEndPoint iep = new IPEndPoint(remoteIP, port);
byte[] bytes = System.Text.Encoding.UTF8.GetBytes(textBoxSend.Text);
try
{
myUdpClient.Send(bytes, bytes.Length, iep);
textBoxSend.Clear();
myUdpClient.Close();
textBoxSend.Focus();
}
catch (Exception err)
{
MessageBox.Show(err.Message, "发送失败");
}
finally
{
myUdpClient.Close();
}
}
private void button1_Click(object sender, RoutedEventArgs e)
{
sendData();
}
}
}
相关文章
- C# 网络编程之基于SMTP发送电子邮件
- C#模板引擎NVelocity实战项目演练
- C# Socket初探
- 《C#高级编程》学习笔记----c#内存管理--栈VS堆
- [C#]exchange发送,收件箱操作类
- EQueue - 一个纯C#写的分布式消息队列介绍2
- 重学c#系列——linq(2) [二十八]
- 重学c#系列——c# 托管和非托管资源与代码相关(四)
- C# 使用LINQ、泛型、Index函数优化switch(或者多条if)语句
- C#.Net操作注册表RegistryKey
- C# POST 发送XML(返回string中可能出现中文乱码问题)
- Atitit. 悬浮窗口的实现 java swing c# .net c++ js html 的实现
- C# 异常处理
- C# 中的"yield"使用
- 【设计模式】职责链模式(C#)