为什么我的线程不能连续工作

时间:2014-03-07 14:01:26

标签: multithreading c#-4.0 network-programming tcpclient

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并且它将继续接收.. bt它不是不幸的.. plz给我解决方案使用此代码..意思是它不是一个类要求或任何东西..我jux想知道如何以这种或任何相关的方式做到这一点..

1 个答案:

答案 0 :(得分: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;
        }));
    }
}

请记住在连接关闭时打破循环,