【问题标题】:sending an xml message to port向端口发送 xml 消息
【发布时间】:2017-05-10 18:23:58
【问题描述】:

对于含糊的问题,我们深表歉意。我正在尝试编写一个 c# 控制台应用程序,它将 xml 消息发送到第 3 方应用程序正在侦听的端口。然后应用程序发回另一条 xml 消息,所以我也需要阅读它。任何建议将不胜感激。

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

【问题讨论】:

标签: c# xml ports


【解决方案1】:

如果您对原始套接字不是很熟悉,我会这样做:

    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[]

【讨论】:

  • 谢谢!很有魅力!
【解决方案2】:

使用 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();

        }
    }

}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2010-12-12
    • 1970-01-01
    • 2011-03-11
    • 2017-06-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多