我用TcpListener.Start()开始监听一个端口了,但是不知道如何应答以及接收数据。
就是当有客户端联过来的时候,会触发什么事件吗?

解决方案 »

  1.   

    不会触犯什么事件,至少不会在什么事件中进行处理:
     public static IPAddress GetServerIP()
            {
                IPHostEntry ieh = Dns.GetHostEntry(Dns.GetHostName());             //获取本地主机的地址
                return ieh.AddressList[0];
            }        private void BeginListen()
            {
                IPAddress ServerIp = GetServerIP();
                IPEndPoint iep = new IPEndPoint(ServerIp, 8000);
                socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);            byte[] byteMessage = new byte[1024];
                socket.Bind(iep);            while (true)
                {
                    try
                    {
                        socket.Listen(5);
                        Socket newSocket = socket.Accept();
                        newSocket.Receive(byteMessage);
                        string msg = Encoding.Default.GetString(byteMessage);
                        msg = msg.Substring(0, 13);
                        if (msg == "ProWorkUpdate")
                        {
                            lbl_BeginInvoke.BeginInvoke(new InvokeDelegateReadData(ReadData));
                        }
                        Thread.Sleep(1000);
                    }
                    catch (SocketException ex)
                    {
                        //MessageBox.Show(ex.Message, "错误提示!");
                        eventLog_SendWorks.WriteEntry("错误提示:" + ex.Message, EventLogEntryType.Error);
                    }
                }        }        public delegate void InvokeDelegateReadData();
            public void ReadData()
            {
                this.timer_ReadData.Enabled = false;
                this.timer_ReadData.Interval = 50;
                this.timer_ReadData.Enabled = true;
            }
        }
    }
      

  2.   

    好像是直接从服务的监听端口的列表中取得的,
     socket.Listen(5); 
                        Socket newSocket = socket.Accept(); 
                        newSocket.Receive(byteMessage); 
                        string msg = Encoding.Default.GetString(byteMessage); 
      

  3.   

    Accept和Receive的调用要分别放到其他线程,否则,调用被阻塞的时候,用户界面会失去响应。
      

  4.   

    服务端代码:

    FrmServer类代码如下

    using System;
    using System.Collections.Generic;
    using System.ComponentModel;
    using System.Data;
    using System.Drawing;
    using System.Text;
    using System.Windows.Forms;
    using System.Net;
    using System.Net.Sockets;
    using System.Threading;
    namespace TCPSERVER
    {
        public partial class FrmServer : Form
        {
            private Socket m_ServerListener = null;
            private ClientInformationCls[] m_clientList;
            delegate void SetTextCallback(string strText);
            private const int MAX_CLIENT = 1;              //client connnecting max number        public FrmServer()
            {
                InitializeComponent();
            }       private static IPAddress GetServerIP()
            {            IPHostEntry ieh = Dns.GetHostEntry(Dns.GetHostName());            return ieh.AddressList[0];        }       private void BeginListen()
            {
                int intPort =8000;            m_clientList=new  ClientInformationCls[ MAX_CLIENT ];            IPAddress ServerIp = GetServerIP();            IPEndPoint iep = new IPEndPoint(ServerIp, intPort);
                m_ServerListener = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                m_ServerListener.Bind(iep);
                m_ServerListener.Listen(1);
            }        private void btnBeginListen_Click(object sender, EventArgs e)
            {
                
                
                try
                {
                    BeginListen();
                    lstServerStatus.Items.Add("Server is starting listening....");                InitClientList();                Thread acceptThread = new Thread(new ThreadStart(AcceptClientThread));
                    acceptThread.Start();
     
                  
                }
                catch (SocketException  ex)
                {
                    MessageBox.Show(ex.ToString());
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.ToString());
                }
            }        private void AcceptClientThread()
            {
                int intClientIndex;            Thread.CurrentThread.IsBackground = true;            try
                {
                    while (true)
                    {
                        intClientIndex = GetFreeClient();
                        if (intClientIndex != -1)
                        {
                            m_clientList[intClientIndex].IsIdle = false;
                            Socket clientSocket = m_ServerListener.Accept();
                            IPEndPoint remoEP = (IPEndPoint)clientSocket.RemoteEndPoint;
                        
                            m_clientList[intClientIndex].ClientIP = remoEP.Address.ToString();
                            m_clientList[intClientIndex].ClientSocket = clientSocket;
                            SetText("connecting from " + m_clientList[intClientIndex].ClientIP);                        Thread DealingThread = new Thread(new ParameterizedThreadStart(RcvSndThread));                        DealingThread.Start(m_clientList[intClientIndex]);                    }
                    }
                }            catch (SocketException ex)
                {
                    MessageBox.Show(ex.ToString());
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.ToString());
                }        }        private void RcvSndThread(object obj)
            {
                Thread.CurrentThread.IsBackground = true;
                ClientInformationCls clientTmp = (ClientInformationCls)obj;
         
                byte[] buffer = new byte[1024];
                int intRcvCount;            try
                {
                    while (clientTmp.ClientSocket.Connected == true)
                    {
                        intRcvCount = clientTmp.ClientSocket.Receive(buffer);
                        SetText(Encoding.Default.GetString(buffer, 0, intRcvCount));                }
                }            catch (SocketException ex)
                {
                    MessageBox.Show(ex.ToString());
                }            catch (Exception ex)
                {
                    MessageBox.Show(ex.ToString());
                }
                     }        private void  InitClientList()
            {
                int i = 0;
                for (i=0; i <= m_clientList.Length-1; i++)
                {
                    m_clientList[i] = new ClientInformationCls();
                    m_clientList[i].ClientHostName="";
                    m_clientList[i].ClientIP = "";
                    m_clientList[i].Index=i;
                    m_clientList[i].IsIdle = true;
                    m_clientList[i].ClientSocket = null;
                }
            }        private int GetFreeClient()
            {
                int i = 0;
               
                for (i = 0; i <= m_clientList.Length - 1; i++)
                {
                    if (m_clientList[i] == null) return -1;
                   
                    if (m_clientList[i].IsIdle == true)
                    {
                        return i;
                    }
                }
                return -1;
            }        private void SetText(string strText)
            {
                if (this.lstServerStatus.InvokeRequired)
                {
                    SetTextCallback d = new SetTextCallback(SetText);
                    this.Invoke(d, new object[] { strText });
                }
                else
                {
                    this.lstServerStatus.Items.Add(strText);
                }
            }    }
    }
    ClientInformationCls.cs代码如下
    using System;
    using System.Collections.Generic;
    using System.Text;
    using System.Net.Sockets;
    namespace TCPSERVER
    {
        class ClientInformationCls
        {
          
            private int m_intClientIndex;             //client's index 
            private string m_strClientIP;
            private string m_strClientHostName;
            private bool  m_blnIsIdle;
            private Socket m_clientSocket;
            public int Index
            {
               get{return m_intClientIndex;}
               set{m_intClientIndex=value;}
            }        public string ClientIP
            {
                get { return m_strClientIP; }
                set { m_strClientIP = value; }
            }        public string ClientHostName
            {
                get { return m_strClientHostName; }
                set { m_strClientHostName = value; }
            }        public bool IsIdle
            {
                get { return m_blnIsIdle; }
                set { m_blnIsIdle = value; }
            }
            public Socket ClientSocket
            {
                get { return m_clientSocket; }
                set { m_clientSocket = value; }
            }
        }
    }其中服务端复杂功能没实现
      

  5.   

    最基础的TCPCLIENT类使用,
    楼主看过书么?没书看MSDN也该会了~~!!!
    http://topic.csdn.net/u/20080202/09/2a639488-5c1e-42d2-9d11-3f6e2ceebc26.html参照6楼我的回贴