2

我想知道是否有人可以帮助我解决我遇到的一个小问题。

我将收到一个将通过 tcp 套接字发送的 xml 文件。我正在尝试创建一个可以充当服务器并通过 tcp 套接字发送 xml 文件的小型应用程序。然后我可以开始测试我的初始应用程序,它将接收和处理这个 xml 文档。

我已经尝试过谷歌并在这个问题上一直遇到死胡同。

4

1 回答 1

2

一种可能的解决方案是将 xml 作为一系列字符串或作为字节数组加载并发送。字节数组方法可能是最简洁的,使用网络库 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”,如果您在同一台机器上同时运行服务器和客户端,这应该可以工作。有关更多信息,还请查看入门如何创建客户端服务器应用程序文章。

于 2013-02-06T00:35:54.787 回答