繁体   English   中英

向端口发送xml消息

[英]sending an xml message to port

为模糊的问题道歉。 我正在尝试编写ac#console应用程序,它将xml消息发送到第三方应用程序正在侦听的端口。 然后应用程序发回另一个xml消息,所以我也需要阅读它。 任何建议将不胜感激。

这种链接显示了我正在尝试做的事情。

如果您对原始套接字不是很熟悉,我会做类似的事情:

    using (var client = new TcpClient())
    {
        client.Connect("host", 2324);
        using (var ns = client.GetStream())
        using (var writer = new StreamWriter(ns))
        {
            writer.Write(xml);
            writer.Write("\r\n\r\n");
            writer.Flush();
        }
        client.Close();
    }

对于较少的抽象,你只需要直接使用Socket实例并手动处理所有编码等,只需给Socket.Send一个byte[]

使用xml Linq

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using System.Xml;
using System.Xml.Linq;


namespace ConsoleApplication50
{
    class Program
    {

        static void Main(string[] args)
        {

                //<?xml version="1.0"?>
                //<active_conditions>
                //  <condition id="12323" name="Sunny"/>
                //  <condition id="13323" name="Warm"/>
                //</active_conditions>

            string header = "<?xml version=\"1.0\"?><active_conditions></active_conditions>";

            XDocument doc = XDocument.Parse(header);

            XElement activeCondition = (XElement)doc.FirstNode;

            activeCondition.Add(new object[] { 
                new XElement("condition", new object[] {
                    new XAttribute("id", 12323),
                    new XAttribute("name", "Sunny")
                }),

                new XElement("condition", new object[] {
                    new XAttribute("id", 13323),
                    new XAttribute("name", "Warm")
                })
            });

            string xml = doc.ToString();

            XDocument doc2 = XDocument.Parse(xml);

            var results = doc2.Descendants("condition").Select(x => new
            {
                id = x.Attribute("id"),
                name = x.Attribute("name")
            }).ToList();

        }
    }

}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM