簡體   English   中英

通過TCP發送和接收XML數據

[英]Sending and Receiving XML data over TCP

我一直在試圖弄清楚如何通過TCP服務器發送和接收XML數據。 我來自java編程背景,所以我有點超出我的深度。 如果我只發送純文本,我的程序可以工作,但是一旦我嘗試發送xml數據,它就會掛起。 服務器永遠不會收到消息。 我一直在尋找代碼來做到這一點,並沒有找到任何運氣,我已經看到許多在線的代碼示例不起作用。 如果你們中的任何一個人能解決這個問題,我將非常感激。

我在這里尋找代碼示例,而不是解釋我應該怎么做才能解決它。 我只用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>

這是我的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();
    }

在你沖洗作家之前不要閱讀。

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

嘗試這樣的事情:

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";
 }

}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM