winfrom中TCP传值

来源:互联网 发布:河南网络流行的歌 编辑:程序博客网 时间:2024/05/17 09:09

在很多网页中找到的答案,也是一位博主写的。

废话不多说上代码


前端:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace Shili2
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }
        private const int bufferSize = 8000;
        NetworkStream sendStream;
        public delegate void showData(string msg);

        private void Form1_Load(object sender, EventArgs e)
        {
        }

        TcpClient client = new TcpClient();
        private void btn_lianjie_Click(object sender, EventArgs e)
        {
            if (txt_IP.Text.Trim() == string.Empty)
            {
                return;
            }
            if (txt_PIC.Text.Trim() == string.Empty)
            {
                return;
            }
            IPAddress ip = IPAddress.Parse(txt_IP.Text);
            client = new TcpClient();
            client.Connect(ip, int.Parse(txt_PIC.Text));
            richTextBox1.AppendText("开始连接服务端....\n");
            richTextBox1.AppendText("已经连接服务端\n");
            //获取用于发送数据的传输流
            sendStream = client.GetStream();
            Thread thread = new Thread(ListenerServer);
            thread.Start();
        }

        private void ListenerServer()
        {
            do
            {
                try
                {
                    int readSize;
                    byte[] buffer = new byte[bufferSize];
                    lock (sendStream)
                    {
                        readSize = sendStream.Read(buffer, 0, bufferSize);
                    }
                    if (readSize == 0)
                        return;
                    richTextBox1.Invoke(new showData(richTextBox1.AppendText), "服务端曰:" + Encoding.Default.GetString(buffer, 0, readSize) + "\n");

                }
                catch
                {
                    richTextBox1.Invoke(new showData(richTextBox1.AppendText), "报错");
                }
                //将缓存中的数据写入传输流
            } while (true);
        }

        private void btn_send_Click(object sender, EventArgs e)
        {
             if (client != null)
            {
                //要发送的信息
                if (txt_send.Text.Trim() == string.Empty)
                    return;
                string msg = txt_send.Text.Trim();
                //将信息存入缓存中
                byte[] buffer = Encoding.Default.GetBytes(msg);
                //lock (sendStream)
                //{
                    sendStream.Write(buffer, 0, buffer.Length);
                //}
                    richTextBox1.AppendText("发送给服务端的数据:" + msg + "\n");
                    txt_send.Text = string.Empty;
            }
        }
    }
}




后端:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace Shili1
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        public delegate void showData(string msg);//委托,防止跨线程的访问控件,引起的安全异常
        private const int bufferSize = 8000;//缓存空间
        private TcpClient client;
        private TcpListener server;

        /// <summary>
        /// 结构体:Ip、端口
        /// </summary>
        struct IpAndPort
        {
            public string Ip;
            public string Port;
        }

        /// <summary>
        /// 开始侦听
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        ///


        private void Form1_Load(object sender, EventArgs e)
        {
            //IPAddress ip = new IPAddress(new byte[] { 127, 1, 1, 1 });
            //TcpListener server = new TcpListener(ip, 8005);

        }

        private void btn_zhenting_Click(object sender, EventArgs e)
        {
            if (txt_IP.Text.Trim() == string.Empty)
            {
                return;
            }
            if (txt_PIC.Text.Trim() == string.Empty)
            {
                return;
            }

            Thread thread = new Thread(reciveAndListener);
            //如果线程绑定的方法带有参数的话,那么这个参数的类型必须是object类型,所以讲ip,和端口号 写成一个结构体进行传递
            IpAndPort ipHePort = new IpAndPort();
            ipHePort.Ip = txt_IP.Text;
            ipHePort.Port = txt_PIC.Text;

            thread.Start((object)ipHePort);
        }
        private void btn_send_Click(object sender, EventArgs e)
        {
            //发送信息给客户端

            if (txt_send.Text.Trim() != string.Empty)
            {
                NetworkStream sendStream = client.GetStream();//获得用于数据传输的流
                byte[] buffer = Encoding.Default.GetBytes(txt_send.Text.Trim());//将数据存进缓存中
                sendStream.Write(buffer, 0, buffer.Length);//最终写入流中
                txt_send.Text = string.Empty;
            }
        }
        /// <summary>
        /// 侦听客户端的连接并接收客户端发送的信息
        /// </summary>
        /// <param name="ipAndPort">服务端Ip、侦听端口</param>
        private void reciveAndListener(object ipAndPort)
        {
            IpAndPort ipHePort = (IpAndPort)ipAndPort;

            IPAddress ip = IPAddress.Parse(ipHePort.Ip);
            server = new TcpListener(ip, int.Parse(ipHePort.Port));
            server.Start();//启动监听
            richTextBox1.Invoke(new showData(richTextBox1.AppendText), "服务端开启侦听....\n");
            //  btnStart.IsEnabled = false;

            //获取连接的客户端对象
            client = server.AcceptTcpClient();
            richTextBox1.Invoke(new showData(richTextBox1.AppendText), "有客户端请求连接,连接已建立!");//AcceptTcpClient 是同步方法,会阻塞进程,得到连接对象后才会执行这一步  

            //获得流
            NetworkStream reciveStream = client.GetStream();

            #region 循环监听客户端发来的信息

            do
            {
                byte[] buffer = new byte[bufferSize];
                int msgSize;
                try
                {
                    lock (reciveStream)
                    {
                        msgSize = reciveStream.Read(buffer, 0, bufferSize);
                    }
                    if (msgSize == 0)
                        return;
                    string msg = Encoding.Default.GetString(buffer, 0, bufferSize);
                    richTextBox1.Invoke(new showData(richTextBox1.AppendText), "\n客户端曰:" + Encoding.Default.GetString(buffer, 0, msgSize));
                }
                catch
                {
                    richTextBox1.Invoke(new showData(richTextBox1.AppendText), "\n 出现异常:连接被迫关闭");
                    break;
                }
            } while (true);

            #endregion
        }
    }
}

总结:虽然相互能够传值成功,但是如果有一方中断,那一方也会中断报错,还在研究当中,参考那个博主的文章链接:www.cnblogs.com/MrALei/p/3582755.html