日期:2014-05-18 浏览次数:20958 次
private void button3_Click(object sender, EventArgs e)
        {
            try
            {
                string msg = "<" + textBox3.Text + ">" + textBox2.Text;
                TcpClient tcpc = new TcpClient(textBox1.Text, 5656);
                NetworkStream tcpStream = tcpc.GetStream();
                StreamWriter reqStreamW = new StreamWriter(tcpStream);
                reqStreamW.Write(msg);
                reqStreamW.Flush();
                tcpStream.Close();
                tcpc.Close();
                richTextBox1.AppendText(msg);
                textBox2.Clear();
            }
            catch (Exception)
            {
                toolStripStatusLabel1.Text = "目标计算机拒绝连接请求!";
            }
        }
        private void button1_Click(object sender, EventArgs e)
        {
            try
            {
                IPAddress ip = new IPAddress(new byte[] { 192, 168, 1, 105 });
                tcplistener = new TcpListener(ip, 1234);
                tcplistener.Start();
                toolStripStatusLabel1.Text = "开始监听……";
                while (true)
                {
                    //等待客户机接入
                    tcpclient = tcplistener.AcceptTcpClient();
                    ns = tcpclient.GetStream();
                    //
                    byte[] buffer = new byte[1024];
                    int bytesRead = ns.Read(buffer, 0, 1024);
                    string msg = System.Text.Encoding.GetEncoding("gb2312").GetString(buffer);
                    this.textBox1.Text = msg;
                }
            }
            catch (System.Security.SecurityException)
            {
                StopListener();
                MessageBox.Show("防火墙安全错误!", "错误",
                    MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
            }
            catch (Exception)
            {
                StopListener();
                toolStripStatusLabel1.Text = "已停止监听!";
            }
        }
        private void button2_Click(object sender, EventArgs e)
        {
            //
            StopListener();
            toolStripStatusLabel1.Text = "已停止监听!";
        }
        private void StopListener()
        {
            ns.Close();
            tcpclient.Close();
            tcplistener.Stop();
        }