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

相关推荐
隐擎fox2 小时前
深入网络风控底层:解密 IP 信誉评分模型、ASN 属性判定与多租户原生网络隔离架构
网络·爬虫·网络协议·tcp/ip·架构·跨境电商·指纹浏览器
胖纸不争4 小时前
嫌桌面 Agent 太重,我“自己”写了一个
ai·c#·net core
Zooproxy全球IP代理5 小时前
海外代理IP纯净度评估:指标、检测与调度实践
网络协议·tcp/ip·php
当青春邂逅吉米多维奇8 小时前
C#图解教程(第5版) 同步方法
开发语言·c#
波力海苔夹心脆6758 小时前
C# 机器视觉实战:单相机引导机械手精准贴合,从拍照、偏差计算(平移+旋转)到坐标补偿全解
开发语言·经验分享·数码相机·c#·视觉检测·.net
Behavior10 小时前
国内下载使用 Unity 6000 踩坑点总结
c#·unity3d·游戏开发
YumiProxy11 小时前
代理IP自动切换避坑指南:会话保持、请求头与错误处理实战
网络·网络协议·tcp/ip·代理模式·ip
czhc114007566311 小时前
一张图从哪来,一个判断往哪走
c#
盛世宏博智慧档案12 小时前
Modbus TCP+PoE以太网温湿度传感器项目部署全流程,附网络调试实操
开发语言·tcp/ip·php·以太网·传感器·温湿度
曹牧1 天前
C#:未被引用的函数
c#