C#用Socket实现TCP客户端

1、TCP客户端实现代码

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、应用程序

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、实现效果
在这里插入图片描述

C#中,Socket用于实现TCP通信的基础,可以创建TCP客户端来连接服务器并发送数据。以下是使用C# Socket类创建TCP客户端的基本步骤: 1. **引用命名空间**: 首先,你需要引用System.Net.Sockets和System.IO命名空间,这两个包含Socket类和其他网络相关的类。 ```csharp using System.Net.Sockets; using System.IO; ``` 2. **创建Socket实例**: 创建一个新的TcpClient对象,它代表了客户端的套接字连接。 ```csharp TcpClient client = new TcpClient(); ``` 3. **连接服务器**: 调用`Connect()`方法,传入服务器的IP地址和端口号。 ```csharp IPEndPoint serverEndpoint = new IPEndPoint(IPAddress.Parse("服务器IP地址"), 端口号); client.Connect(serverEndpoint); ``` 4. **获取网络流**: 获取`NetworkStream`对象,这是实际的数据传输通道。 ```csharp NetworkStream networkStream = client.GetStream(); ``` 5. **读取和写入数据**: 使用StreamReader读取从服务器接收的数据,StreamWriter发送数据。 ```csharp StreamReader reader = new StreamReader(networkStream); StreamWriter writer = new StreamWriter(networkStream); // 发送数据到服务器 string message = "要发送的消息"; writer.WriteLine(message); writer.Flush(); // 接收服务器响应 string response = reader.ReadLine(); Console.WriteLine("Server responded: " + response); ``` 6. **关闭连接**: 完成操作后记得关闭流和客户端连接。 ```csharp reader.Close(); writer.Close(); networkStream.Close(); client.Close(); ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

大浪淘沙胡

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值