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

相关推荐
加号36 小时前
【C#】 文件与目录管理:创建、删除操作的技术解析
开发语言·c#
壹方秘境7 小时前
ChatTCP是怎么像Wireshark那样识别TCP重传、乱序和心跳保活的
网络协议·tcp/ip·wireshark
用户3952409988010 小时前
SqlSugar 连接 PostgreSQL 报错 42P01: relation does not exist 的排查与修复
c#
2601_9618752411 小时前
法考考试时间安排及科目|时间表|资料已整理
开发语言·c#·inverted-index·suffix-tree·sstable·r-tree·lsm-tree
ServBay11 小时前
你跟高级 C# 工程师的区别,就是这8个开发技巧
后端·c#·.net
liulilittle12 小时前
KCC:在 BBR 思路上的一次探索
网络·tcp/ip·算法·bbr·通信·拥塞控制·kcc
сокол14 小时前
【网安-研判-WireShark流量分析】端口扫描流量分析(高频短连接、SYN 扫描、ICMP 存活探测、扫描 IP / 时段 / 工具指纹)
网络·tcp/ip·wireshark
2601_9618752416 小时前
法考备考计划表|学习计划|资料已整理
java·开发语言·学习·eclipse·tomcat·c#·hibernate
Y学院17 小时前
C#游戏脚本开发全流程(Unity通用完整版)
游戏·unity·c#
行走__Wz17 小时前
【网工入门-eNSP模拟-01】ip地址配置
网络·tcp/ip·智能路由器