接收信息需要在循环里进行,而receive本身是阻塞方法,所以你不用担心cpu占漫,完全可以使用while(true)或者加一个退出条件
while(true) {
try
{
// **STEP 2** 接收信息
byte[] receiveBytes=receive.Receive(ref RemoteIpEndPoint);
//信息转换并输出
string returnData=Encoding.ASCII.GetString(receiveBytes);
this.richTextBox1.AppendText(returnData);
// **STEP 3**关闭连接
receive.Close();
}
catch(Exception e)
{
MessageBox.Show(e.ToString());
}
}
while(true) {
try
{
// **STEP 2** 接收信息
byte[] receiveBytes=receive.Receive(ref RemoteIpEndPoint);
//信息转换并输出
string returnData=Encoding.ASCII.GetString(receiveBytes);
this.richTextBox1.AppendText(returnData);
// **STEP 3**关闭连接
receive.Close();
}
catch(Exception e)
{
MessageBox.Show(e.ToString());
}
}
xxdneu(xxd) 联系一下啊,
问点问题,好不好?
当然它生成时,就不可能接收到了.
你可以把它设为全局的,
{
Thread start = new Thread(new ThreadStart(Receive));
start.Start();
}
private void Receive()
{
// **STEP 1**
UdpClient receive= new UdpClient(8080);
IPEndPoint RemoteIpEndPoint=null;
try
{
while(true)
{
// **STEP 2** receiving the data
byte[] receiveBytes=receive.Receive(ref RemoteIpEndPoint);
//Conver the data
string returnData=Encoding.ASCII.GetString(receiveBytes);
this.richTextBox1.Text= (DateTime.Now+"\r\n"+returnData);
// **STEP 2**
receive.Close();
}
}
catch(Exception e)
{
MessageBox.Show(e.ToString());
}
}
server向lan中所有的client发送广播!问题就在接收上 。。client只能接收到一条。
参看http://cht.gotdotnet.com/quickstart/util/srcview.aspx?path=/quickstart/howto/samples/net/TCPUDP/Chat.src&file=CS\chat.cs&font=3public static void Listener() { //
// The listener waits for data to come
// and buffers it Thread.Sleep(2000); // make sure client2 is receiving Encoding ASCII = Encoding.ASCII; while(!m_Done) {
IPEndPoint endpoint = null;
Byte[] data = m_Client.Receive(ref endpoint); String strData = ASCII.GetString(data); if( strData.IndexOf(":@") > 0 ) {
//
// we received a termination indication
// now we have to decide if it is from
// our main thread shutting down, or
// from someone else
//
Char [] separators = {':'};
String [] vars = strData.Split(separators); if( vars[0] == m_szHostName ) {
//
// this is from ourselves, therefore we
// end now
//
Console.WriteLine("正在關閉接聽項執行緒..."); //
// this should have been done by main thread, but we
// do it again for safety
//
m_Done = true;
}
else {
//
// this is from someone else
//
Console.WriteLine("{0} 已經離開會話", vars[0]);
}
}
else {
//
// this is normal data received from others
// as well as ourselves
// check to see if it is from ourselves before
// we print
//
if(strData.IndexOf(":") > 0) {
Char [] separators = {':'};
String [] vars = strData.Split(separators); if( vars[0] != m_szHostName ) {
Console.WriteLine(strData);
}
}
}
} Console.WriteLine("接聽項執行緒已經完成...");
return;
}