我一直在试图弄清楚如何通过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();
}
答案 0 :(得分:3)
在你冲洗作家之前不要阅读。
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();
答案 1 :(得分:1)
尝试这样的事情:
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";
}
}