C#通过TCP发送List<string>

编程入门 行业动态 更新时间:2024-10-27 08:25:41

C#通过<a href=https://www.elefans.com/category/jswz/34/1769077.html style=TCP发送List<string>"/>

C#通过TCP发送List<string>

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客户端的StreamStream 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包管理器安装它。

更多推荐

C#通过TCP发送List<string>

本文发布于:2023-11-16 06:40:06,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1614137.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:TCP   List   string

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!