C#用Socket实现TCP客户端

1、TCP客户端实现代码

csharp 复制代码
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace PtLib.TcpClient
{
    public delegate void TcpClientReceivedEventHandler(TcpClientStateEventArgs args);
    public class TcpClient
    {
        //接收委托
        public event TcpClientReceivedEventHandler TcpReceived;
        //
        private string _ip = "127.0.0.1";
        //
        private int _port = 8080;
        //
        Socket socket = null;
        //
        Thread thread = null;

        /// <summary>
        /// 
        /// </summary>
        /// <param name="ip"></param>
        /// <param name="port"></param>
        public TcpClient(string ip,int port) 
        { 
            _ip = ip;
            _port = port;
        }
        /// <summary>
        /// 
        /// </summary>
        public void Open()
        {
            socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            IPEndPoint endPoint=new IPEndPoint(IPAddress.Parse(_ip), _port);
            socket.Connect(endPoint);

            thread = new Thread(Receiver);
            thread.IsBackground = true;
            thread.Start();
        }

        private void Receiver()
        {
            while (true)
            {
                byte[] buffer = new byte[1024*1024];
                int length = socket.Receive(buffer);
                if(length > 0)
                {
                    byte[] b = new byte[length];
                    Buffer.BlockCopy(buffer, 0, b, 0, length);
                    TcpClientStateEventArgs args = new TcpClientStateEventArgs();
                    args.buffer = b;
                    TcpReceived?.Invoke(args);
                }
            }
        }

        public void Send(byte[] data)
        {
            socket.Send(data);
        }
        /// <summary>
        /// 
        /// </summary>
        public void Close() 
        {
            socket?.Close();
            thread?.Abort();
            socket = null;
            thread = null;
        }
    }
    /// <summary>
    /// Tcp状态事件参数类
    /// </summary>
    public class TcpClientStateEventArgs : EventArgs
    {
        public byte[] buffer = null;
    }
}

2、应用程序

csharp 复制代码
using PtLib.TcpServer;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace TcpClient
{
    public partial class Form1 : Form
    {
        PtLib.TcpClient.TcpClient tcpClient = null;
        /// <summary>
        /// 
        /// </summary>
        public Form1()
        {
            InitializeComponent();
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnConnect_Click(object sender, EventArgs e)
        {
            if (btnConnect.Text.Equals("连接"))
            {
                btnConnect.Text = "断开";
                string ip = tbClientIp.Text.Trim();
                int port = int.Parse(tbClientPort.Text.Trim());
                tcpClient = new PtLib.TcpClient.TcpClient(ip, port);
                tcpClient.Open();
                tcpClient.TcpReceived += TcpClient_TcpReceived;
            }
            else
            {
                btnConnect.Text = "连接";
                tcpClient.Close();
            }
        }

        private void TcpClient_TcpReceived(PtLib.TcpClient.TcpClientStateEventArgs args)
        {
            string str = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss:fff") + ":";
            str += Encoding.UTF8.GetString(args.buffer);
            this.Invoke(new Action(() =>
            {
                lbxReceive.Items.Add(str);
            }));
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnSend_Click(object sender, EventArgs e)
        {
            string str = tbxSend.Text.Trim();
            byte[] sendBytes = Encoding.UTF8.GetBytes(str);
            tcpClient.Send(sendBytes);
        }
    }
}

3、实现效果

相关推荐
朱皮皮呀5 分钟前
C++入门基础
开发语言·c++·引用·内联函数·auto关键字·命名空间·缺省参数
学习不好的电气仔20 分钟前
基于虚拟阻抗的逆变器下垂控制环流抑制策略MATLAB仿真
开发语言·matlab
原机小子21 分钟前
掌握MATLAB中的数据类型转换技巧
开发语言·matlab
比花花解语35 分钟前
Java中Integer的缓存池是怎么实现的?
java·开发语言·缓存
学步_技术1 小时前
Python编码系列—Python团队开发工作流:高效协作的艺术
开发语言·python·团队开发
柳鲲鹏1 小时前
编译成功!QT/6.7.2/Creator编译Windows64 MySQL驱动(MinGW版)
开发语言·qt·mysql
三玖诶1 小时前
如何在 Qt 的 QListWidget 中逐行添加和显示数据
开发语言·qt
追逐远方的梦1 小时前
二级C语言2023-3易错题
c语言·开发语言
一个很帅的帅哥1 小时前
实现浏览器的下拉加载功能(类似知乎)
开发语言·javascript·mysql·mongodb·node.js·vue·express
极客先躯1 小时前
java和kotlin 可以同时运行吗
android·java·开发语言·kotlin·同时运行