通过 TCP 发送和接收 XML 数据 [英] Sending and Receiving XML data over TCP

查看:82
本文介绍了通过 TCP 发送和接收 XML 数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在尝试弄清楚如何通过 TCP 服务器发送和接收 XML 数据.我来自 Java 编程背景,所以我在这里有点超出我的深度.如果我只发送纯文本,我的程序就可以工作,但是一旦我尝试发送 xml 数据,它就会挂起.服务器永远不会收到消息.我一直在寻找代码来做到这一点,但没有找到任何运气,我在网上看到很多代码示例都不起作用.请如果你们中的任何人能解决这个问题,我将不胜感激.

I've been trying to figure out how to send and receive XML Data over a TCP Server. I'm coming from a java programming background so i'm a bit out of my depth here. My program works if i'm sending just plain text, however once I try to send the xml data it just hangs. The server never receives the message. I've been searching for code to do this and haven't found any luck, i've seen lots of code samples online that don't work. please if any of you can solve this problem I would be very grateful.

请我在这里寻找代码示例,而不是解释我应该怎么做来修复它.我只写了几天 C# 代码.这是示例 XML 请求.

Please I'm looking for code samples here, not explanations on what I should do to fix it. I've only been coding C# for a few days. Here is the sample XML Request.

    <?xml version="1.0" encoding="utf-8"?>
    <ClientRequest>
      <Product>AGENT</Product>
      <Method>GET_SYSTEM_INFO</Method>
      <ClientId>UMOHB</ClientId>
      <Params>
        <Param Value="umohb" Key="username" />
        <Param Value="password" Key="password" />
        <Param Value="localhost" Key="hostname" />
      </Params>
    </ClientRequest>

这是我的 TCP 客户端代码

Here is my TCP Client Code

    public static void sendStringRequest(String hostname, int port, String message)
    {
        String response = String.Empty;
        TcpClient client = getConnection(hostname, port);

        Console.WriteLine(message);

        NetworkStream stream = client.GetStream();
        StreamWriter writer = new StreamWriter(stream, Encoding.UTF8);
        writer.AutoFlush = false;
        writer.Write(Encoding.UTF8.GetBytes(message).Length);
        writer.Write(message);
        writer.Flush();

        StreamReader reader = new StreamReader(stream, Encoding.UTF8);
        response = reader.ReadLine();

        stream.Close();
    }

推荐答案

在你刷完作者之前不要阅读.

Don't read until you have flushed the writer.

NetworkStream stream = client.GetStream();
StreamWriter writer = new StreamWriter(stream, Encoding.UTF8);
writer.AutoFlush = false;
writer.Write(Encoding.UTF8.GetBytes(message).Length);
writer.Write(message);
writer.Flush();

StreamReader reader = new StreamReader(stream, Encoding.UTF8);
response = reader.ReadLine();

stream.Close();

这篇关于通过 TCP 发送和接收 XML 数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆