C# 通过 TCP 发送和接收 XML 数据

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9362959/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-09 07:02:07  来源:igfitidea点击:

Sending and Receiving XML data over TCP

c#xmlsocketstcptcpclient

提问by greenkode

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.

我一直在试图弄清楚如何通过 TCP 服务器发送和接收 XML 数据。我来自 Java 编程背景,所以我在这里有点超出我的深度。如果我只发送纯文本,我的程序就可以工作,但是一旦我尝试发送 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.

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

    <?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>

Here is my TCP Client Code

这是我的 TCP 客户端代码

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

采纳答案by jgauffin

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

回答by Kamil Emeleev

Try something like this:

尝试这样的事情:

public static string sendStringRequest(String hostname, int port, string message) {

 try {
  byte[] data = System.Text.Encoding.ASCII.GetBytes(message);

  TcpClient client = new TcpClient(hostname, port);

  NetworkStream stream = client.GetStream();
  BinaryWriter writer = new BinaryWriter(stream);

  //first 4 bytes - length!
  writer.Write(Convert.ToByte("0"));
  writer.Write(Convert.ToByte("0"));
  writer.Write(Convert.ToByte("0"));
  writer.Write(Convert.ToByte(data.Length));
  writer.Write(data);

  data = new Byte[256];

  // String to store the response ASCII representation.
  String responseData = String.Empty;

  Int32 bytes = stream.Read(data, 0, data.Length);

  responseData = System.Text.Encoding.ASCII.GetString(data, 4, (bytes - 4));

  // Close everything.
  stream.Close();
  client.Close();
  return responseData;
 } catch (ArgumentNullException e) {
  MessageBox.Show("ArgumentNullException: " + e);
  return "null";
 } catch (SocketException e) {
  MessageBox.Show("SocketException: " + e);
  return "null";
 }

}