我是靠谱客的博主 端庄山水,最近开发中收集的这篇文章主要介绍c# TCP/IP通信,觉得挺不错的,现在分享给大家,希望可以做个参考。

概述

首先是监听

namespace TcpIpTest
{
    public partial class ListenerForm : Form
    {
        private Thread listenThread;
        public bool keepReading=false;

        public ListenerForm()
        {
            InitializeComponent();
        }

        private void actionButton_Click(object sender, EventArgs e)
        {
            if (!keepReading)
            {
                string address = IPAddressTextBox.Text;
                string port = IPPortTextBox.Text;
                string addressRegex = @"^d+.d+.d+.d+$";
                string portRegx = @"^d+$";
                if (Regex.IsMatch(address, addressRegex) && Regex.IsMatch(port, portRegx))
                {
                    keepReading = true;
                    //监听的是本地的IP地址,因为电脑可以同时链接到多个网络,所以一台电脑可以同时有不同的IP地址,这里需要指明要监听哪个IP的哪个端口
                    listenThread = new Thread(() => ipListen(IPAddress.Parse(address), int.Parse(port)));
                    listenThread.Start();
                    this.stateLabel.Text = "正在监听";
                    this.actionButton.Text = "停止监听";
                }
                else
                {
                    MessageBox.Show("请填写正确的IP地址和端口");
                }
            }
            else
            {
                keepReading = false;
                this.stateLabel.Text = "空闲";
                this.actionButton.Text = "开始监听";
            }
        }
        private void ipListen(IPAddress address, int port)
        {
            TcpListener listener = new TcpListener(address, port);
            listener.Start();
            OneString oneString = new OneString(changeResultTextBox);
            while (keepReading)//这是一个阀,来控制是否脱离线程,因为要把listener停掉,所以不能用abort来关闭线程
            {
                if (listener.Pending())//这是判断是否有输入的,必须要加这个判断,不然线程就会在下面的AcceptTcpClient卡住
                {
                     using (TcpClient client = listener.AcceptTcpClient())
                    {
                        //接收
                        NetworkStream netStream = client.GetStream();
                        byte[] receiveBytes = new byte[client.ReceiveBufferSize];
                        netStream.Read(receiveBytes, 0, client.ReceiveBufferSize);
                        string str = Encoding.Default.GetString(receiveBytes).TrimEnd('');
                        //返回
                        byte[] sendBytes = Encoding.Default.GetBytes("receive!");
                        netStream.Write(sendBytes, 0, sendBytes.Length);
                        netStream.Close();
                    }
                }
            }
            listener.Stop();
        }
        private delegate void OneString(string content);

        private void changeResultTextBox(string content)
        {
            this.resultTextBox.Text += content;
        }
        private void ListenerForm_FormClosing(object sender, FormClosingEventArgs e)
        {
            keepReading = false;
        }
    }
}

然后是发送

namespace TcpIpTest
{
    public partial class SendForm : Form
    {
        public SendForm()
        {
            InitializeComponent();
        }

        private void sendButton_Click(object sender, EventArgs e)
        {
            string address = IPAddressTextBox.Text;
            string port = IPPortTextBox.Text;
            string addressRegex = @"^d+.d+.d+.d+$";
            string portRegx = @"^d+$";
            string content = this.contentTextBox.Text;
            if (Regex.IsMatch(address, addressRegex) && Regex.IsMatch(port, portRegx) && !string.IsNullOrWhiteSpace(content))
            {
                using (TcpClient client = new TcpClient())
                {
                    try
                    {
                        //这里是目标的IP地址和端口
                        client.Connect(address, int.Parse(port));
                        NetworkStream netStream = client.GetStream();
                        byte[] sendBytes = Encoding.Default.GetBytes(this.contentTextBox.Text);
                        netStream.Write(sendBytes, 0, sendBytes.Length);
                        //接收
                        byte[] receiveBytes = new byte[client.ReceiveBufferSize];
                        netStream.Read(receiveBytes, 0, client.ReceiveBufferSize);
                        string str = Encoding.Default.GetString(receiveBytes).TrimEnd('');
                        MessageBox.Show(str);
                        netStream.Close();
                    }
                    catch (Exception e1)
                    {
                        if (e1 is SocketException)
                        {
                            MessageBox.Show("无法ping通");
                        }
                    }
                }
            }
            else
            {
                MessageBox.Show("请填写正确的IP地址、端口和内容");
            }
        }
    }
}

 

最后

以上就是端庄山水为你收集整理的c# TCP/IP通信的全部内容,希望文章能够帮你解决c# TCP/IP通信所遇到的程序开发问题。

如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(59)

评论列表共有 0 条评论

立即
投稿
返回
顶部