C# 处理TCP数据的类(服务端)

using System;
using System.Collections.Generic;
using System.Net;
using System.Net.Sockets;
using System.Threading;

namespace TestDemo
{
    /// <summary>
    /// 处理TCP数据的类(服务端)
    /// </summary>
    public class TcpService
    {
        /// <summary>
        /// TCP监听对象
        /// </summary>
        private TcpListener tcpListener;

        /// <summary>
        /// 创建TCP监听
        /// </summary>
        public void CreateListener(int port)
        {
            // 监听对象
            tcpListener = new TcpListener(IPAddress.Any, port);
            tcpListener.Start();
            // 独立线程监听
            Thread thread = new Thread(StartListener);
            thread.Start();
        }

        /// <summary>
        /// 开始监听
        /// </summary>
        private void StartListener()
        {
            while (true)
            {
                try
                {
                    // TCP监听
                    TcpClient tcpClient = tcpListener.AcceptTcpClient();
                    // 多线程处理数据
                    Thread thread = new Thread(new ParameterizedThreadStart(delegate { DealTcpData(tcpClient); }));
                    thread.Start();
                }
                catch (Exception ex)
                {
                    // 错误日志
                    Log.WriteError(ex);
                }
            }
        }

        /// <summary>
        /// 处理TCP数据
        /// <para>lv结构:数据的前4个字节(int),记录了数据区的长度</para>
        /// <para>注意:数据结构根据实际使用情况而定</para>
        /// </summary>
        private void DealTcpData(TcpClient tcpClient)
        {
            try
            {
                if (tcpClient.Connected)
                {
                    // 取得流
                    NetworkStream networkStream = tcpClient.GetStream();
                    networkStream.ReadTimeout = 500;
                    networkStream.WriteTimeout = 500;
                    #region 接收数据
                    // 接收数据储存
                    List<byte> list = new List<byte>();
                    // 数据区总长度
                    byte[] lenArr = new byte[4];
                    networkStream.Read(lenArr, 0, lenArr.Length);
                    int dataLen = BitConverter.ToInt32(lenArr, 0);
                    // 读取数据区数据
                    int total = 0;
                    // 每次读取的数据大小
                    int arrLen = 1024;
                    while (true)
                    {
                        // 读取数据
                        byte[] arr = new byte[arrLen];
                        int len = networkStream.Read(arr, 0, arr.Length);
                        for (int i = 0; i < len; i++)
                        {
                            list.Add(arr[i]);
                        }
                        // 判断数据的是否读取完成
                        total += len;
                        if (dataLen - total <= 0)
                        {
                            break;
                        }
                        if (dataLen - total < arrLen)
                        {
                            arrLen = dataLen - total;
                        }
                        Thread.Sleep(0);
                    }
                    // 根据功能或实际情况处理接收的数据
                    byte[] receiveData = list.ToArray();
                    #endregion
                    #region 发送数据
                    // 取得数据
                    // 根据功能或实际情况做成需要发送的数据
                    byte[] dataArr = new byte[] { 0x01, 0x02, 0x03, 0x04 }; // 测试数据
                    if (dataArr != null)
                    {
                        // 数据长度
                        byte[] lengArr = BitConverter.GetBytes(dataArr.Length);
                        // 拼接数据头(lv结构)
                        byte[] sendArr = new byte[lengArr.Length + dataArr.Length];
                        lengArr.CopyTo(sendArr, 0);
                        dataArr.CopyTo(sendArr, 4);
                        // 发送数据
                        try
                        {
                            lock (networkStream)
                            {
                                networkStream.Write(sendArr, 0, sendArr.Length);
                            }
                        }
                        catch { }
                    }
                    #endregion
                }
            }
            catch (Exception ex)
            {
                // 错误日志
                Log.WriteError(ex);
            }
            finally
            {
                // 判断TCP对象是否连接
                if (tcpClient != null)
                {
                    JudgeTcpConnection(tcpClient);
                }
            }
        }

        /// <summary>
        /// 判断TCP对象是否连接
        /// </summary>
        private void JudgeTcpConnection(TcpClient tcpClient, int timeout = 3)
        {
            try
            {
                DateTime time = DateTime.Now;
                while (true)
                {
                    // 超时时间判断
                    if (time.AddSeconds(timeout) < DateTime.Now)
                    {
                        break;
                    }
                    // 连接状态判断
                    if (!tcpClient.Connected)
                    {
                        break;
                    }
                    else
                    {
                        bool flag = tcpClient.Client.Poll(1000, SelectMode.SelectRead);
                        if (flag)
                        {
                            break;
                        }
                    }
                    Thread.Sleep(0);
                }
            }
            catch (Exception ex)
            {
                // 错误日志
                Log.WriteError(ex);
            }
            finally
            {
                // 关闭连接
                tcpClient.Close();
            }
        }
    }
}

原文地址 https://www.cnblogs.com/smartnn/p/16635584.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值