我用C#写了个UDP测试程序,在VS2008下运行很好,而脱离开发环境运行就接收不到UDP
老顽童 2010-09-15 10:44:56 请问,是何种原因?
namespace UdpTest
{
public partial class Form1 : Form
{
UdpClient udp=new UdpClient();
Thread threads;
bool first = true;
void RecieveData()
{
while (true)
{
try
{
if (udp.Available > 0)
{
// MessageBox.Show("A");
int i;
IPEndPoint ipEndPoint = new IPEndPoint(IPAddress.Any, 0);
//IPEndPoint ipEndPoint = null;
byte[] buffer = udp.Receive(ref ipEndPoint);
string text = "";
for (i = 0; i < buffer.Length; i++)
text += buffer[i].ToString("X2") + " ";
numericUpDown1.Value = numericUpDown1.Value + 1;
SetText(text);
}
}
catch
{
}
}
}
private delegate void SetTextCallback(string text);
private void SetText(string text)
{
if (this.richTextBox1.InvokeRequired)
{
SetTextCallback d = new SetTextCallback(SetText);
this.Invoke(d, new object[] { text });
}
else
{
this.richTextBox1.AppendText(text + "\n");
}
}
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
CheckForIllegalCrossThreadCalls = false;
Control.CheckForIllegalCrossThreadCalls = false;
threads = new Thread(new ThreadStart(RecieveData));
threads.Priority = ThreadPriority.Highest;
threads.IsBackground = true;
//threads.Start();
}
private void button1_Click(object sender, EventArgs e)
{
int i;
byte[] data = new byte[] { 0x0EB, 0x90, 0x81, 0x99, 0x81, 0x13, 0x0B0, 04, 3, 0x0FE, 0x0FE, 0x68, 0x13, 0x32, 0x03, 0x0, 0x0, 0, 0x68, 1, 2, 0x43, 0x00c3, 0x21, 0x16, 0x0b9, 0x99, 0x0B1 };
IPEndPoint remoteEndPoint = new IPEndPoint(IPAddress.Parse(txtAddress.Text), int.Parse(txtPort.Text));
IPEndPoint address = new IPEndPoint(IPAddress.Any, 0);
if (first)
{
udp = new UdpClient(address);
first = false;
threads.Start();
}
udp.Send(data, 28, remoteEndPoint);
string text = "";
for (i = 0; i < data.Length; i++)
text += data[i].ToString("X2") + " ";
numericUpDown2.Value ++;
richTextBox2.Text += text+"\n";
}
private void Form1_FormClosed(object sender, FormClosedEventArgs e)
{
threads.Abort();
udp.Close();
}
private void button2_Click(object sender, EventArgs e)
{
timer1.Enabled = true;
}
private void button3_Click(object sender, EventArgs e)
{
timer1.Enabled = false;
}
}
}