C#用Socket进行TCP通信,如何接收并解析Xml的数据
时间: 2024-02-20 12:00:33 浏览: 130
C#上位机基础学习-基于SOCKET实现与PLC服务器的TCP通信(二).docx
5星 · 资源好评率100%
在进行TCP通信时,接收到的数据是以字节流的形式传输的,因此需要将接收到的字节流转换为字符串,再解析字符串中的XML数据。
以下是一个示例代码,演示了如何使用C#的Socket进行TCP通信,并接收并解析XML数据:
```csharp
using System;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Xml;
class TcpListenerExample
{
public static void Main()
{
TcpListener server = null;
try
{
// Set the TcpListener on port 13000.
Int32 port = 13000;
IPAddress localAddr = IPAddress.Parse("127.0.0.1");
// TcpListener server = new TcpListener(port);
server = new TcpListener(localAddr, port);
// Start listening for client requests.
server.Start();
// Buffer for reading data
Byte[] bytes = new Byte[256];
String data = null;
// Enter the listening loop.
while (true)
{
Console.Write("Waiting for a connection... ");
// Perform a blocking call to accept requests.
// You could also use server.AcceptSocket() here.
TcpClient client = server.AcceptTcpClient();
Console.WriteLine("Connected!");
data = null;
// Get a stream object for reading and writing
NetworkStream stream = client.GetStream();
int i;
// Loop to receive all the data sent by the client.
while ((i = stream.Read(bytes, 0, bytes.Length)) != 0)
{
// Translate data bytes to a ASCII string.
data = Encoding.ASCII.GetString(bytes, 0, i);
Console.WriteLine("Received: {0}", data);
// Parse the XML data
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.LoadXml(data);
// Do something with the XML data
XmlNodeList nodes = xmlDoc.GetElementsByTagName("message");
foreach (XmlNode node in nodes)
{
Console.WriteLine("Message: {0}", node.InnerText);
}
// Send a response back to the client.
byte[] msg = Encoding.ASCII.GetBytes("Message received.");
stream.Write(msg, 0, msg.Length);
Console.WriteLine("Sent: {0}", "Message received.");
}
// Shutdown and end connection
client.Close();
}
}
catch (SocketException e)
{
Console.WriteLine("SocketException: {0}", e);
}
finally
{
// Stop listening for new clients.
server.Stop();
}
Console.WriteLine("\nHit enter to continue...");
Console.Read();
}
}
```
在上面的代码中,当接收到数据时,我们将其转换为字符串,并使用XmlDocument对象来解析XML数据。在本例中,我们假设XML数据包含一个名为“message”的元素,我们使用GetElementsByTagName方法获取所有名为“message”的元素,并遍历它们以输出其InnerText属性。你可以根据实际情况修改代码以适应你的XML数据结构。
阅读全文