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包管理器安装它。

相关推荐
猿长大人7 小时前
C# | JSON 序列化中的多态接口处理:基于 Attribute 实现精准 $type 控制
c#·json
一位狮子座的程序员11 小时前
如何用RAG解决AI智能体的知识盲区?
开发语言·c#
March.s11 小时前
IP 存储核心 iSCSI:原理拆解 + 无报错实战指南
网络·网络协议·tcp/ip
Nemo_XP12 小时前
C# gridlookupedit选中内容重复还原操作
服务器·前端·c#
猿长大人13 小时前
C# | 函数式编程入门
开发语言·c#·.net
wsad053214 小时前
CentOS Stream 10 配置静态 IP 完整指南
linux·tcp/ip·centos
似水এ᭄往昔15 小时前
【Linux网络编程】--TCP_Socket
linux·网络·tcp/ip
unityのkiven15 小时前
C# 中的奇异递归模板模式:MonoSingleton<T> 的实现
java·开发语言·c#
雪隐15 小时前
WPF + MVVM 实战系列02-告别 INPC 手写时代,做个体面的现代 WPF 人
前端·后端·c#
月落归舟15 小时前
Redis 三种消息队列实现方案
数据库·redis·list