我想知道是否有人能够帮助我解决我遇到的小问题。
我将收到一个将通过 tcp 套接字发送的 xml 文件。我正在尝试创建一个小型应用程序,它可以充当服务器并通过 tcp 套接字发送 xml 文件。然后,我可以开始测试将接收和处理此 xml 文档的初始应用程序。
我已经尝试过谷歌,但在这个问题上一直遇到死胡同。
最佳答案
一种可能的解决方案是将 xml 作为一系列字符串或字节数组加载并发送。字节数组方法可能是最简洁的,使用 network library networkcomms.net调用发送的应用程序将如下所示:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using NetworkCommsDotNet;
namespace Client
{
class Program
{
static void Main(string[] args)
{
byte[] bytesToSend = File.ReadAllBytes("filename.xml");
TCPConnection.GetConnection(new ConnectionInfo("127.0.0.1", 10000)).SendObject("XMLData", bytesToSend);
Console.WriteLine("Press any key to exit client.");
Console.ReadKey(true);
NetworkComms.Shutdown();
}
}
}
和服务器:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using NetworkCommsDotNet;
namespace Server
{
class Program
{
static void Main(string[] args)
{
NetworkComms.AppendGlobalIncomingPacketHandler<byte[]>("XMLData", (packetHeader, connection, incomingXMLData) =>
{
Console.WriteLine("Received XMLData");
File.WriteAllBytes("filename.xml", incomingXMLData);
});
TCPConnection.StartListening(true);
Console.WriteLine("Server ready. Press any key to shutdown server.");
Console.ReadKey(true);
NetworkComms.Shutdown();
}
}
}
您显然需要从网站下载 NetworkCommsDotNet DLL,以便可以将其添加到“使用 NetworkCommsDotNet”引用中。另请参阅客户端示例中的服务器 IP 地址当前为“127.0.0.1”,如果您在同一台计算机上运行服务器和客户端,这应该可以工作。欲了解更多信息,请查看 getting started或how to create a client server application文章。
关于c# - TCP 套接字上的 XML,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14692181/