【发布时间】:2012-03-10 21:38:19
【问题描述】:
我一直试图弄清楚如何通过 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();
}
【问题讨论】:
-
@JohnSaunders 谢谢,非常感谢您的意见...您有没有想过为什么可以选择在您的问题或回复中添加代码示例?
标签: c# xml sockets tcp tcpclient