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();
}
}
}