XML over TCP socket

2019-03-01 06:39发布

问题:

I was wondering if someone would be able to help me with a small problem I am having.

I will be receiving a xml file that is going to be sent through a tcp socket. I am trying to create a small application that can act as the server and send a xml file through a tcp socket. I can then start testing my initial application that will be receiving and processing this xml document.

I have tried Google and keep running into dead ends on this one.

回答1:

One possible solution is to load the xml either as a series of strings or as a byte array and send that. The byte array approach might be the most concise, using the network library networkcomms.net the application calling the sending would look something like this:

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();
        }
    }
}

and the server:

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();
        }
    }
}

You will obviously need to download the NetworkCommsDotNet DLL from the website so that you can add it in the 'using NetworkCommsDotNet' reference. Also see the server IP address in the client example is currently "127.0.0.1", this should work if you run both the server and client on the same machine. For more information also checkout the getting started or how to create a client server application articles.



标签: c# xml sockets tcp