我一直在想如何通过TCP服务器发送和接收XML数据。我来自java编程背景,所以我在这里深入一点。我的程序工作,如果我只发送纯文本,但是一旦我尝试发送它只是挂起的XML数据。服务器从不接收消息。 我一直在寻找代码来做到这一点,并没有找到任何运气,我已经看到很多在线代码示例不起作用。如果您有任何人可以解决这个问题,我会非常感激。通过TCP发送和接收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谢谢你,你的输入,非常感谢......你有没有想过,为什么你要在你的问题或响应添加代码示例的选项? – greenkode 2012-02-20 15:38:37