• C#通过TCP发送List<string>


    1. using System;
    2. using System.IO;
    3. using System.Net.Sockets;
    4. using System.Text;
    5. using System.Collections.Generic;
    6. public static void SendList<string>(Stream stream, List<string> list)
    7. {
    8. // 将List对象转换为字节数组
    9. byte[] data = Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(list));
    10. // 获取数据长度
    11. int length = data.Length;
    12. // 创建一个ArraySegment对象,包含数据长度和数据本身
    13. ArraySegment<byte> segment = new ArraySegment<byte>(data, 0, length);
    14. // 发送数据长度
    15. stream.Write(segment.ToArray(), 0, length);
    16. }
    17. public static List<string> ReceiveList<string>(Stream stream)
    18. {
    19. // 读取数据长度
    20. int length = stream.ReadInt32();
    21. // 创建一个字节数组,用于接收数据
    22. byte[] data = new byte[length];
    23. // 读取数据
    24. stream.Read(data, 0, length);
    25. // 将字节数组转换为List对象
    26. return JsonConvert.DeserializeObjectstring>>(Encoding.UTF8.GetString(data));
    27. }
    28. public class Client
    29. {
    30. public static void Main()
    31. {
    32. // 创建一个TCP客户端
    33. TcpClient client = new TcpClient("127.0.0.1", 8080);
    34. // 获取TCP客户端的Stream
    35. Stream stream = client.GetStream();
    36. // 创建一个List对象
    37. List<string> list = new List<string> { "Hello", "World" };
    38. // 发送List对象
    39. SendList<string>(stream, list);
    40. // 接收List对象
    41. List<string> receivedList = ReceiveList<string>(stream);
    42. // 输出接收到的List对象
    43. Console.WriteLine("Received List: " + string.Join(",", receivedList));
    44. // 关闭TCP客户端
    45. client.Close();
    46. }
    47. }

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

  • 相关阅读:
    数据结构---链表(java)
    Android的多线程和异步处理
    JZ85 连续子数组的最大和(二)
    零时科技 || BXH攻击事件分析
    学习-Java输入输出之文件字节IO流之拆分文件
    华为RH2288 V3安装 Linux 系统,安装过程心得
    Pikachu靶场——SSRF 服务端请求伪造
    六、鼎捷T100生产管理之生产入库管理篇
    oauth2.0使用JWT存储token连接数据库
    嵌入式网络接口之MAC芯片与PHY芯片
  • 原文地址:https://blog.csdn.net/qq_31418645/article/details/134256351