之前的一篇文章 TCP/IP简单示例文件发送 - 实用工具_软件教程_.net_c#-有码挺好个人博客 (cisharp.com) 讲了c#.net如何基于WatsonTcp实现Tcp客户端服务端通信。但是WatsonTcp对交互数据进行过包装;所以不适合用于与原生Tcp客户端、服务端交互。本文就来介绍另一个Tcp框架,此框架基于原生Tcp简单封装,不影响与原生Tcp数据交互,框架名称叫SimpleTcp;本文例子均以SimpleTcp为基础,从而实现Tcp通信。

SimpleTcp开源地址:https://github.com/jchristn/SimpleTcp

示例程序地址:https://github.com/zonevg/SimpleTcpExample

c# tcp客户端
c# tcp服务端

客户端代码

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

namespace SimpleTcpClient
{
    public partial class FrmMain : Form
    {
        public FrmMain()
        {
            InitializeComponent();
        }

        private SimpleTcp.SimpleTcpClient client;
        private void btn_link_Click(object sender, EventArgs e)
        {
            if (btn_link.Text == "连接")
            {
                client = new SimpleTcp.SimpleTcpClient($"{txt_ip.Text.Replace(" ", "")}", int.Parse(txt_port.Text));
                client.Events.Connected += OnConnected;
                client.Events.DataReceived += OnDataReceived;
                client.Events.Disconnected += OnDisconnected; ;
                client.Connect();
                //设置断线重连间隔,秒为单位
                client.ConnectWithRetries(10);
                btn_link.Text = "断开";
            }
            else
            {
                btn_link.Text = "连接";
                client.Disconnect();
            }
        }
        private void OnConnected(object sender, SimpleTcp.ClientConnectedEventArgs e)
        {
            ShowLog("连接成功");
        }
        private void OnDataReceived(object sender, SimpleTcp.DataReceivedEventArgs e)
        {
            ShowLog(Encoding.UTF8.GetString(e.Data));
        }
        private void OnDisconnected(object sender, SimpleTcp.ClientDisconnectedEventArgs e)
        {
            ShowLog($"断开连接,原因:{e.Reason}");
        }
        private void ShowLog(string msg)
        {
            this.BeginInvoke((Action)delegate
            {
                ri_log.Text = ri_log.Text.Insert(0, $"{DateTime.Now.ToString("yyyyy-MM-dd HH:mm:ss")} {msg}\r\n");
            });
        }
        private void btn_send_Click(object sender, EventArgs e)
        {
            client.Send(txt_msg.Text);
            txt_msg.Text = string.Empty;
        }
    }
}

服务端代码

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

namespace SimpleTcpServer
{
    public partial class FrmMain : Form
    {
        public FrmMain()
        {
            InitializeComponent();
        }
        private SimpleTcp.SimpleTcpServer server;
        private void btn_link_Click(object sender, EventArgs e)
        {
            if (btn_link.Text == "启动")
            {
                server = new SimpleTcp.SimpleTcpServer($"{txt_ip.Text.Replace(" ", "")}", int.Parse(txt_port.Text));
                server.Events.ClientConnected += OnConnected;
                server.Events.DataReceived += OnDataReceived;
                server.Events.ClientDisconnected += OnDisconnected;
                btn_link.Text = "停止";
                server.Start();
            }
            else
            {
                btn_link.Text = "启动";
                server.Stop();
                server.Dispose();
            }
        }
        private void OnConnected(object sender, SimpleTcp.ClientConnectedEventArgs e)
        {
            this.BeginInvoke((Action)delegate
            {
                cbo_client.Items.Add(e.IpPort);
            });
            ShowLog("客户端连接成功");
        }
        private void OnDataReceived(object sender, SimpleTcp.DataReceivedEventArgs e)
        {
            ShowLog(Encoding.UTF8.GetString(e.Data));
        }
        private void OnDisconnected(object sender, SimpleTcp.ClientDisconnectedEventArgs e)
        {
            ShowLog($"断开连接,原因:{e.Reason}");
        }
        private void ShowLog(string msg)
        {
            this.BeginInvoke((Action)delegate
            {
                ri_log.Text = ri_log.Text.Insert(0, $"{DateTime.Now.ToString("yyyyy-MM-dd HH:mm:ss")} {msg}\r\n");
            });
        }
        private void btn_send_Click(object sender, EventArgs e)
        {
            if (cbo_client.Text != "")
            {
                server.Send(cbo_client.Text, txt_msg.Text);
                txt_msg.Text = string.Empty;
            }
            else
            {
                MessageBox.Show("请先选中客户端");
            }
        }

    }
}
最后修改:2022 年 09 月 30 日
免责声明:本站为个人博客,博客所发布的一切修改补丁、注册机和注册信息及软件的文章仅限用于学习和研究目的;不得将上述内容用于商业或者非法用途。否则,一切后果请用户自负。本站信息来自网络,版权争议与本站无关,您必须在下载后的24个小时之内,从您的电脑中彻底删除上述内容。访问和下载本站内容,说明您已同意上述条款。