当前位置:编程学习 > C#/ASP.NET >>

有关AcceptTcpClient的问题

 public partial class Form1 : Form
    {
        private Server server        public Form1()
        {
            InitializeComponent();
            server = new Server();;//建立服务端对象
            server.dlg = this;
            textBox1.Text = server.LocalIP.ToString();
            textBox4.Text = server.port.ToString();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            server.StartListening();//启动侦听
        }
    }
********************************************************************
 public class Server//服务端类
    {
        public IPAddress LocalIP;
        private string LocalName;
        private TcpListener listener;
        private TcpClient client;
        public int port;
        private int count;
        private const int Max=2;
        private ReomteClient[] RClient;
        public Form1 dlg;
        public Server()
        {
            LocalName = Dns.GetHostName();
            LocalIP = Dns.GetHostEntry(LocalName).AddressList[0];
            port=8500;
            listener = new TcpListener(LocalIP, port);
            RClient = new ReomteClient[Max];
            count = 0;
        }
        public void StartListening()
        {
            listener.Start();
            while (count<Max)
            {
                client = listener.AcceptTcpClient();//程序死在这里
                dlg.textBox2.Text = client.Client.RemoteEndPoint.ToString();
                RClient[count] = new ReomteClient(client);
                RClient[count].dlg = dlg;
                count++;
            }
        }
    }
当我按下button1,会调用Server类的StartListening(),启动服务端侦听,但程序死在了listener.AcceptTcpClient()。
类似的程序在控制台上运行是正常的,不知是什么原因!在坛子里看到过相似的问题,最后的解答是listener.AcceptTcpClient()写在form_load里了,但小弟愚笨,看不懂这个解答什么意思,求大侠赐教! --------------------编程问答-------------------- 帮楼主顶了。 --------------------编程问答-------------------- AcceptTcpClient命令是不应该放在主程序线程中的,要将他放在另一个线程里,因此执行它后将挂起,并等待,当有客户接入后,该命令返回一个TcpClient实例,并向下运行。 --------------------编程问答-------------------- 楼上正解
补充:.NET技术 ,  C#
CopyRight © 2012 站长网 编程知识问答 www.zzzyk.com All Rights Reserved
部份技术文章来自网络,