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

相关推荐
阿蒙Amon7 小时前
C#每日面试题-Array和ArrayList的区别
java·开发语言·c#
不一样的故事1268 小时前
下的 “Wi-Fi参数配置” 列表,但您当前选中的导航菜单项是 “IP规划”。您遇到的 “IP加载不出来” 问题,很可能
网络协议·tcp/ip·华为
i橡皮擦9 小时前
TheIsle恐龙岛读取游戏基址做插件(C#语言)
开发语言·游戏·c#·恐龙岛·theisle
qq_3168377512 小时前
IP网段冲突 配置指定ip使用指定的网络接口发送,而不经过默认网关
服务器·网络·tcp/ip
枷锁—sha13 小时前
彻底解决 Google Gemini 报错:异常流量与 IP 地址冲突排查指南
网络·网络协议·tcp/ip
逐梦苍穹13 小时前
不用公网 IP,把内网服务安全发布到公网:ZeroNews 快速上手
网络协议·tcp/ip·安全·内网穿透
木子020415 小时前
Java8集合list.parallelStream() 和 list.stream() 区别
数据结构·list
用户219916797039115 小时前
C# 14 中的新增功能
c#
蜂蜜黄油呀土豆16 小时前
计算机网络中的传输层:深入解析 TCP 协议
网络协议·tcp/ip·计算机网络·三次握手·网络排查