日期:2014-05-18  浏览次数:20841 次

TCP网络通信如何发送数据?
小弟刚接触C#,对其概念还不是理解很深,遇到这个问题,请高手赐教,如何执行SendMsg,提示未能实例化?
C# code

        TcpListener dataListener = null;

        Socket dataSocket = null;

        private void FormMain_Load(object sender, EventArgs e)
        {
            BeginListen();
            tmr.Enabled = true;
        }   
     
        private void BeginListen()
        {
            string IP = Dns.GetHostAddresses(Dns.GetHostName())[0].ToString();

            IPEndPoint dataEndPoint = new IPEndPoint(IPAddress.Parse(IP), 6005);
            dataListener = new TcpListener(dataEndPoint);
            dataListener.Start();
        }

        private void timer1_Tick(object sender, EventArgs e)
        {
            DataListen();
        }

        private void DataListen()
        {
            if (dataListener.Pending())
            {
                dataSocket = dataListener.AcceptSocket();

                //Thread ShowMsgThread = new Thread(new ThreadStart(ShowMsg));
                //ShowMsgThread.Start();
            }
        }

        private void ShowMsg()
        {
            byte[] buffer = new byte[1024 * 1024 * 5];
            try
            {
                while (true)
                {
                    dataSocket.Receive(buffer);
                    string bufferLine = Encoding.Default.GetString(buffer, 0, buffer.Length);
                    string[] bufferTine = bufferLine.Split(new string[] { "|" }, StringSplitOptions.None);

                   
                        if (bufferTine[0] == txbIP.Text)
                        {
                            if (bufferTine[1] == Dns.GetHostAddresses(Dns.GetHostName())[0].ToString())
                            {
                                if (bufferTine[2] == "connect")
                                {

                                }
                                                            }
                        }
                }
            }
            catch (Exception)
            {
                //异常
            }
        }

        private void SendMsg(string Msg)
        {
            string ServerIP = Dns.GetHostAddresses(Dns.GetHostName())[0].ToString();
            string ClientIP = txbIP.Text;
            byte[] SendMsg = Encoding.Default.GetBytes(ServerIP + "|" + ClientIP + "|" + Msg);

            dataSocket.Send(SendMsg);
        }



------解决方案--------------------
断点看看,哪句出错,错误提示很清楚,有空对象,自己调试一下
------解决方案--------------------
C# code

 private void DataListen()
        {
            if (dataListener.Pending())
            {
                dataSocket = dataListener.AcceptSocket();
            }
        }