C#通过TCP发送List<string>

cs 复制代码
using System;
using System.IO;
using System.Net.Sockets;
using System.Text;
using System.Collections.Generic;

public static void SendList<string>(Stream stream, List<string> list)
{
   // 将List<string>对象转换为字节数组
   byte[] data = Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(list));

   // 获取数据长度
   int length = data.Length;

   // 创建一个ArraySegment对象,包含数据长度和数据本身
   ArraySegment<byte> segment = new ArraySegment<byte>(data, 0, length);

   // 发送数据长度
   stream.Write(segment.ToArray(), 0, length);
}

public static List<string> ReceiveList<string>(Stream stream)
{
   // 读取数据长度
   int length = stream.ReadInt32();

   // 创建一个字节数组,用于接收数据
   byte[] data = new byte[length];

   // 读取数据
   stream.Read(data, 0, length);

   // 将字节数组转换为List<string>对象
   return JsonConvert.DeserializeObject<List<string>>(Encoding.UTF8.GetString(data));
}

public class Client
{
   public static void Main()
   {
       // 创建一个TCP客户端
       TcpClient client = new TcpClient("127.0.0.1", 8080);

       // 获取TCP客户端的Stream
       Stream stream = client.GetStream();

       // 创建一个List<string>对象
       List<string> list = new List<string> { "Hello", "World" };

       // 发送List<string>对象
       SendList<string>(stream, list);

       // 接收List<string>对象
       List<string> receivedList = ReceiveList<string>(stream);

       // 输出接收到的List<string>对象
       Console.WriteLine("Received List: " + string.Join(",", receivedList));

       // 关闭TCP客户端
       client.Close();
   }
}

请注意,这个示例代码使用了Json.NET库来将List<string>对象转换为JSON字符串,然后将JSON字符串转换为字节数组。如果您没有安装Json.NET库,可以使用NuGet包管理器安装它。

相关推荐
Xzq2105098 分钟前
网络编程套接字(TCP)
服务器·网络·tcp/ip
小曹要微笑20 分钟前
C#什么是方法
c#·c#方法·方法是什么·什么是方法
阿蒙Amon37 分钟前
C#常用类库-详解CsvHelper
开发语言·数据库·c#
军训猫猫头40 分钟前
5.正弦波生成器:支持连续相位与可控重置 C# + WPF 完整示例
c#·.net·wpf
心前阳光1 小时前
Mirror网络库插件使用4
java·linux·网络·unity·c#·游戏引擎
笑川 孙1 小时前
iperf3 UDP测试踩坑:TCP流量正常,UDP服务端收不到流量;
网络协议·tcp/ip·udp
B2_Proxy2 小时前
什么是住宅 IP?住宅代理的工作原理与应用指南
服务器·网络·tcp/ip
格林威3 小时前
工业相机图像高速存储(C#版):先存内存,后批量转存方法,附海康相机实战代码!
开发语言·人工智能·数码相机·计算机视觉·c#·视觉检测·海康相机
sanshizhang3 小时前
C#如何获取CAD的对象并修改
windows·c#·cad插件