基于WPF开发局域网聊天工具,在用udp做上线功能时遇到的问题
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
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.Sockets;
using System.Threading;
using System.Net;
namespace LANTransfer
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
private Thread td;
//private Thread td2;
public MainWindow()
{
InitializeComponent();
}
private void Window_Loaded(object sender, RoutedEventArgs e)
{
td = new Thread(new ThreadStart(startListen));
td.IsBackground = true;
td.Start();
sendOnline();
}
private void startListen()
{
try
{
while (true)
{
IPEndPoint RemoteIpEndPoint = new IPEndPoint(IPAddress.Any, 0);
UdpClient udpListener = new UdpClient(new IPEndPoint(IPAddress.Any, 3828));
string receive = "";
byte[] bytes = udpListener.Receive(ref RemoteIpEndPoint);
string localAddress = new IPAddress(Dns.GetHostByName(Dns.GetHostName()).AddressList[0].Address).ToString();
udpListener.Close();
if (localAddress == RemoteIpEndPoint.Address.ToString())
{
continue;
}
sendOnline();
receive = RemoteIpEndPoint.Address.ToString() + Encoding.UTF8.GetString(bytes);
this.Dispatcher.Invoke(new Action(delegate { textBox1.Text = receive; }));
}
}
catch (Exception e)
{
MessageBox.Show("侦听出错!"+e.Message);
}
}
private void sendOnline()
{
try
{
IPEndPoint localPoint = new IPEndPoint(new IPAddress(Dns.GetHostByName(Dns.GetHostName()).AddressList[0].Address), 3828);
UdpClient onlineMess = new UdpClient(localPoint);
onlineMess.Connect(IPAddress.Broadcast, 3828);
byte[] bytes = Encoding.UTF8.GetBytes("我上线了!");
onlineMess.Send(bytes, bytes.Length);
onlineMess.Close();
this.Dispatcher.Invoke(new Action(delegate { textBox2.Text = "已广播上线信息!"; }));
}
catch (Exception e)
{
MessageBox.Show("发送上线失败!"+e.Message);
}
}
private void sendOffline()
{
try
{
IPEndPoint localPoint = new IPEndPoint(new IPAddress(Dns.GetHostByName(Dns.GetHostName()).AddressList[0].Address), 3828);
UdpClient offlineMess = new UdpClient(localPoint);
offlineMess.Connect(IPAddress.Broadcast, 3838);
byte[] bytes = Encoding.UTF8.GetBytes("我下线了!");
offlineMess.Send(bytes, bytes.Length);
offlineMess.Close();
}
catch (Exception e)
{
MessageBox.Show("发送下线失败!"+e.Message);
}
}
private void Window_Closed(object sender, EventArgs e)
{
sendOffline();
}
}
}