const int bufSize = 1024;
        private IPAddress myIP;
        private IPEndPoint myServer;
        private Socket connectSock;
        private Thread thread1;
        private rcvData[] rcvBuf = new rcvData[bufSize];
        private int iWrite = -1, iRead = -1;        struct rcvData
        {
            public byte[] Data;
        }        private void Connection()
        {
            string IPString;
            string PortString;
            IPString = TxtServerIP.Text.Trim();
            PortString = TxtServerPort.Text.Trim();
            try
            {
                myIP = IPAddress.Parse(IPString);            }
            catch
            {
                MessageBox.Show("輸入的IP地址格式不正確");
                return;
            }
            try
            {
                myServer = new IPEndPoint(myIP, Int32.Parse(PortString));
                connectSock = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);                connectSock.Connect(myServer);
                thread1 = new Thread(new ThreadStart(target));
                thread1.Start();            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }        private void target()
        {
            while (true)
            {
                ReceiveString();
            }
        }        private int ReceiveString()
        {
            int rcvLen;
            byte[] rec = new byte[1024];            rcvLen = connectSock.Receive(rec, rec.Length, 0);            if (rcvLen < 1)
            {
                return 0;
            }            while (iWrite + 1 == iRead || (iWrite == 1023 && iRead == 0))
            {
            }
            if (iWrite == 1023)
            {
                iWrite = 0;
            }
            else
            {
                iWrite++;
            }            int i;
            rcvBuf[iWrite].Data = new Byte[rcvLen];
            for (i = 0; i < rcvLen; i++)
            {
                rcvBuf[iWrite].Data[i] = rec[i];
            }
            return rcvLen;
        }        private void CmdConnect_Click(object sender, EventArgs e)
        {
            Connection();
            MessageBox.Show("連接成功!", "信息");
        }        private void timer1_Tick(object sender, EventArgs e)
        {
            if (iRead == iWrite) return;            if (iRead + 1 == bufSize)
            {
                iRead = 0;
            }
            else
            {
                iRead++;
            }
            int i;
            byte[] tmpByte = new Byte[rcvBuf[iRead].Data.Length - 8];            byte subcmd;
            string msg;            subcmd = rcvBuf[iRead].Data[6];            for (i = 0; i < rcvBuf[iRead].Data.Length - 8; i++)
            {
                tmpByte[i] = rcvBuf[iRead].Data[i + 8];
            }            switch (subcmd)
            {
                case 16:
                    msg = System.Text.Encoding.Default.GetString(tmpByte);
                    break;
                case 55:
                    msg = System.Text.Encoding.Default.GetString(tmpByte);
                    break;
                default:
                    msg = null;
                    break;
            }
            ShowRcvMsg(msg);
        }        private void ShowRcvMsg(string rcvmsg)
        {
            if (rcvmsg == null) return;            TxtNetData.Text+=rcvmsg;
            TxtNetData.ScrollToCaret();
        }

解决方案 »

  1.   

    代码很简单,但是有不少处写的不是很规范: // 缓冲区大小
    const int bufSize = 1024; 
    // IP地址
            private IPAddress myIP; 
    // 网络节点
            private IPEndPoint myServer; 
    // 套接字
            private Socket connectSock; 
    // 线程
            private Thread thread1; 
    // 接受缓冲区
            private rcvData[] rcvBuf = new rcvData[bufSize]; 
    // 读写标志
            private int iWrite = -1, iRead = -1;  // 接受数据结构
            struct rcvData 
            { 
                public byte[] Data; 
            }  /// <summary>
    /// 使用TCP协议打开Socket连接到执行的IP
    /// </summary>
            private void Connection() 
            { 
                string IPString; 
                string PortString; 
                IPString = TxtServerIP.Text.Trim(); 
                PortString = TxtServerPort.Text.Trim(); 
                try 
                { 
                    myIP = IPAddress.Parse(IPString);             } 
                catch 
                { 
                    MessageBox.Show("輸入的IP地址格式不正確"); 
                    return; 
                } 
                try 
                { 
    // 实例化网络节点
                    myServer = new IPEndPoint(myIP, Int32.Parse(PortString)); 
                    connectSock = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); 
    // 连接到目标
                    connectSock.Connect(myServer); 
    // 创建接受数据线程
                    thread1 = new Thread(new ThreadStart(target)); 
    // 开始接收数据
                    thread1.Start();             } 
                catch (Exception ex) 
                { 
                    MessageBox.Show(ex.Message); 
                } 
            }  /// <summary>
    /// 接受数据线程体
    /// </summary>
            private void target() 
            { 
                while (true) 
                { 
                    ReceiveString(); 
                } 
            }  /// <summary>
    /// 读取接收到的数据
    /// </summary>
    /// <returns></returns>
            private int ReceiveString() 
            { 
                int rcvLen; 
                byte[] rec = new byte[1024];  // 读取端口接收到的数据
                rcvLen = connectSock.Receive(rec, rec.Length, 0);             if (rcvLen < 1) 
                { 
                    return 0; 
                }             while (iWrite + 1 == iRead || (iWrite == 1023 && iRead == 0)) 
                { 
                } 
                if (iWrite == 1023) 
                { 
                    iWrite = 0; 
                } 
                else 
                { 
                    iWrite++; 
                }             int i; 
                rcvBuf[iWrite].Data = new Byte[rcvLen]; 
                for (i = 0; i < rcvLen; i++) 
                { 
                    rcvBuf[iWrite].Data[i] = rec[i]; 
                } 
                return rcvLen; 
            }  /// <summary>
    /// 连接按钮
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
            private void CmdConnect_Click(object sender, EventArgs e) 
            { 
                Connection(); 
                MessageBox.Show("連接成功!", "信息"); 
            }  /// <summary>
    /// 定时器,显示接收线程收到的数据
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
            private void timer1_Tick(object sender, EventArgs e) 
            { 
                if (iRead == iWrite) return;             if (iRead + 1 == bufSize) 
                { 
                    iRead = 0; 
                } 
                else 
                { 
                    iRead++; 
                } 
                int i; 
                byte[] tmpByte = new Byte[rcvBuf[iRead].Data.Length - 8];             byte subcmd; 
                string msg;             subcmd = rcvBuf[iRead].Data[6];             for (i = 0; i < rcvBuf[iRead].Data.Length - 8; i++) 
                { 
                    tmpByte[i] = rcvBuf[iRead].Data[i + 8]; 
                }             switch (subcmd) 
                { 
                    case 16: 
                        msg = System.Text.Encoding.Default.GetString(tmpByte); 
                        break; 
                    case 55: 
                        msg = System.Text.Encoding.Default.GetString(tmpByte); 
                        break; 
                    default: 
                        msg = null; 
                        break; 
                } 
                ShowRcvMsg(msg); 
            }  /// <summary>
    /// 显示数据到TxtBox控件上
    /// </summary>
    /// <param name="rcvmsg"></param>
            private void ShowRcvMsg(string rcvmsg) 
            { 
                if (rcvmsg == null) return;             TxtNetData.Text+=rcvmsg; 
                TxtNetData.ScrollToCaret(); 
            }
      

  2.   

    呵呵,标准的tcp/ip通讯教学代码