gpt4 book ai didi

c# - 如何使用套接字发送或返回 List

转载 作者:行者123 更新时间:2023-11-30 15:34:58 24 4
gpt4 key购买 nike

还有一个服务器和客户端套接字。我想学习如何发送 List<T> , IEnumerable<T>对象到客户端到服务器或服务器到客户端。我想将服务器端 TaskManager 线程列表发送到客户端。此代码逐行发送,我想发送完整列表。我该怎么做?

private static IEnumerable<string> TaskManager()
{
List<string> lst = new List<string>();

foreach (System.Diagnostics.Process p in
Process.GetProcesses().OrderBy(o => o.ProcessName))
{
lst.Add(p.ProcessName + "_" + p.Id);
}
return lst.AsParallel();
}

....
....
....

while (true)
{
Socket socket = Listener.AcceptSocket();
try
{
//open stream
Stream stream = new NetworkStream(socket);
StreamReader sr = new StreamReader(stream);
StreamWriter sw = new StreamWriter(stream);
sw.AutoFlush = true;
while (true)
{
Parallel.ForEach(
TaskManager(), item=>
sw.WriteLine(item)
);
}

stream.Close();
stream.Dispose();

}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}

Console.WriteLine("Disconnected: {0}", socket.RemoteEndPoint);
socket.Close();
socket.Dispose();
}

最佳答案

您可以使用 BinaryFormatter 来序列化和反序列化一个 List。

using System.Runtime.Serialization.Formatters.Binary;

// Server side
Stream stream = new NetworkStream(socket);
var bin = new BinaryFormatter();
bin.Serialize(stream, TaskManager());

// Client side
Stream stream = new NetworkStream(socket);
var bin = new BinaryFormatter();
var list = (List<string>)bin.Deserialize(stream);

关于c# - 如何使用套接字发送或返回 List<T>,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15588279/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com