private void Listen ( ) 

try 

tlTcpListen = new TcpListener (System.Net.IPAddress.Any, port ) ; 
tlTcpListen.Start ( ) ; 
this.richTextBox1.Text = "正在监听..." ; 
tcClient = tlTcpListen.AcceptTcpClient ( ) ;
nsStream = tcClient.GetStream ( ) ; 
// srRead = new StreamReader(nsStream);
this.richTextBox1.Text = "已经连接!"; 
while( blistener ) //循环侦听

if (nsStream.CanRead)
{
byte[] bytes = new byte[1024];
string szMsg = "";
int nRead = 0;
// string sMessage = srRead.ReadLine();
do 
{
nRead = nsStream.Read(bytes,0,bytes.Length);
szMsg = 
String.Concat(szMsg,System.Text.Encoding.ASCII.GetString(bytes,0,nRead));
if (szMsg == "message")
{ }
this.richTextBox1.Text = szMsg;
}
while(nsStream.DataAvailable);
}
// this.richTextBox1.Items.Add ( sTime + " " + sMessage ) ; 

}  catch ( Exception ex) 

MessageBox.Show (ex.Message) ; 

}我用一个客户端发消息,第一次能收到,再用另外一个客户端法一个另外的消息就不灵了!为什么呢!?

解决方案 »

  1.   

    把 nsStream = tcClient.GetStream ( ) ; 写到循环里
      

  2.   

    private void Listen ( ) 

    try 

    tlTcpListen = new TcpListener (System.Net.IPAddress.Any, port ) ; 
    tlTcpListen.Start ( ) ; 
    this.richTextBox1.Text = "正在监听..." ; 

    while( blistener ) //循环侦听

                                         tcClient = tlTcpListen.AcceptTcpClient ( ) ;
    nsStream = tcClient.GetStream ( ) ; 
    // srRead = new StreamReader(nsStream);
    this.richTextBox1.Text = "已经连接!";  if (nsStream.CanRead)
    {
    byte[] bytes = new byte[1024];
    string szMsg = "";
    int nRead = 0;
    // string sMessage = srRead.ReadLine();
    do 
    {
    nRead = nsStream.Read(bytes,0,bytes.Length);
    szMsg = 
    String.Concat(szMsg,System.Text.Encoding.ASCII.GetString(bytes,0,nRead));
    if (szMsg == "message")
    { }
    this.richTextBox1.Text = szMsg;
    }
    while(nsStream.DataAvailable);
    }
    // this.richTextBox1.Items.Add ( sTime + " " + sMessage ) ; 

    }  catch ( Exception ex) 

    MessageBox.Show (ex.Message) ; 

    }