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、实现效果

相关推荐
GO兔10 分钟前
开篇:GORM入门——Go语言的ORM王者
开发语言·后端·golang·go
好开心啊没烦恼24 分钟前
Python 数据分析:numpy,抽提,整数数组索引与基本索引扩展(元组传参)。听故事学知识点怎么这么容易?
开发语言·人工智能·python·数据挖掘·数据分析·numpy·pandas
future14121 小时前
C#学习日记
开发语言·学习·c#
king_harry2 小时前
Java程序-OceanBase Connector/J 示例
开发语言
傻啦嘿哟3 小时前
Python 办公实战:用 python-docx 自动生成 Word 文档
开发语言·c#
翻滚吧键盘3 小时前
js代码09
开发语言·javascript·ecmascript
q567315233 小时前
R语言初学者爬虫简单模板
开发语言·爬虫·r语言·iphone
rzl023 小时前
java web5(黑马)
java·开发语言·前端
时序数据说4 小时前
为什么时序数据库IoTDB选择Java作为开发语言
java·大数据·开发语言·数据库·物联网·时序数据库·iotdb
jingling5554 小时前
面试版-前端开发核心知识
开发语言·前端·javascript·vue.js·面试·前端框架