2014-03-07 32 views
0
using System; 
using System.Collections.Generic; 
using System.ComponentModel; 
using System.Data; 
using System.Drawing; 
using System.Linq; 
using System.Text; 
using System.Windows.Forms; 
using System.Net; 
using System.Net.Sockets; 
using System.IO; 
using System.Threading; 


namespace MultiClientServer 
{ 
    public partial class Form1 : Form 
    { 
     public Form1() 
     { 
      InitializeComponent(); 
     } 



     private void button1_Click(object sender, EventArgs e) 
     { 
      TcpListener listner = new TcpListener(new IPEndPoint(IPAddress.Loopback, 8000)); 
      listner.Start(); 
      textBox1.Text += "Started TCP Server"+Environment.NewLine; 
      listner.BeginAcceptTcpClient(new AsyncCallback(Accept), listner); 
     } 

     void Accept(IAsyncResult result) 
     { 
      textBox1.Invoke(new MethodInvoker(delegate() 
       { 
        textBox1.Text += "Client Request Arrived" + Environment.NewLine; 
       })); 
      TcpListener listner1 = (TcpListener)result.AsyncState; 
      TcpClient client = listner1.EndAcceptTcpClient(result); 
      textBox1.Invoke(new MethodInvoker(delegate() 
       { 
        textBox1.Text += "Client Request Approved" + Environment.NewLine; 
       })); 
      Thread th = new Thread(new ParameterizedThreadStart(ContinueRcv)); 
      th.Start(client); 
     } 

     void ContinueRcv(object obj) 
     { 
      TcpClient client = (TcpClient)obj; 
      StreamReader sr = new StreamReader(client.GetStream()); 
      textBox1.Invoke(new MethodInvoker(delegate() 
       { 
        textBox1.Text += sr.ReadLine() + Environment.NewLine; 
       })); 
     } 
    } 
} 

我试图让这个应用程序,这样,当一个客户端连接不是一个新的线程将b创建,它将b在继续接受.. BT是不是很遗憾.. PLZ给我的解决方案使用此代码..意味着它不是一个类的要求或任何..我jux想知道如何做到这一点或以任何相关的方式..为什么我的线程不能连续工作

+0

“客户端”和“SR”不应该从recv线程作为表单类的成员进行访问,以开始。你需要在线程创建时将“客户端”传递给线程,否则它很容易被另一个接收到的线程覆盖。因为类似的原因,'sr'应该是线程中的局部。 –

+0

明白了..让我检查这个.. – rummykhan

+0

我已经检查没有改变代码..我可以做thix而在我的线程bt我不认为这是一个很好的做法..你有什么想法..? ? – rummykhan

回答

1

线程是不是被连续调用,您的代码在线程块中需要连续调用,因为您的线程负责调用ContinueRcv线程以此方法结束,

如果你想继续接收来自Stream你需要调用的StreamReader的的ReadLine()在某些无限循环的数据,

void ContinueRcv(object obj) 
{ 
    TcpClient client = (TcpClient)obj; 
    StreamReader sr = new StreamReader(client.GetStream()); 
    while (true) 
    { 
     if (!connection) { // when connection closed, abort, terminated 
      break; 
     } 
     msg = sr.ReadLine(); 
     textBox1.Invoke(new MethodInvoker(delegate() 
     { 
      textBox1.Text += msg + Environment.NewLine; 
     })); 
    } 
} 

记住打破循环的时候连不上,