基于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();
}
}
}
问题说明一下:我先在虚拟机上和物理机上做了实验(都是win7系统),物理机发的广播虚拟机可以收到,而虚拟机发的广播在物理机收不到。然后我在另一台物理机上做了实验(和我自己的机子在同一局域网,xp系统),就抛出“通常每个套接字地址(协议/网络地址/端口)只允许使用一次”异常,并且连广播都没有发出去。刚接触网络编程,请高手赐教。。。
[解决办法]
参见 http://www.cnblogs.com/xiaozhi_5638/p/3169641.html
局域网UDP通信