Получение XML данных по TCP порту - C#

Узнай цену своей работы

Формулировка задачи:

Здравствуйте, Пишу приложение, которое будет получать XML-данные по TCP, а затем писать эти данные в базу данных. Нашёл в интернете пример как отправлять и принимать XML по TCP-порту. Использовал его в своём приложении. XML отправляется, принимается, парсится и пишется в базу только, если прописать сам XML-код в тексте программы. А надо, чтобы программа открывала соединение на указанном порту и прослушивала этот порт, ожидая XML-сообщения от любого приложения (например отправки сообщения по телнету), а затем писала бы это сообщение в базу. Вопрос, как это сделать? Можете ли привести пример кода? Или дать ссылку на реализацию подобной программы. C# знаю слабо, поэтому желательны примеры кода Отправляю то что пока у меня получилось. Спасибо!
Листинг программы
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. using System.Net;
  6. using System.IO;
  7. using System.Net.Sockets;
  8. using System.Threading;
  9. using System.Xml;
  10.  
  11. namespace ConsoleApplication2
  12. {
  13. class XMLBlaster
  14. {
  15. Thread myThread;
  16. public XMLBlaster()
  17. {
  18. myThread = new Thread(Start);
  19. }
  20. public void Begin()
  21. {
  22. myThread.Start();
  23. }
  24. //This will listen for a connection on port 12345, and send a tiny XML document
  25. //to the first person to connect.
  26. protected void Start()
  27. {
  28. TcpListener tcp = new TcpListener(IPAddress.Any, 12345);
  29. tcp.Start(1);
  30. TcpClient client = tcp.AcceptTcpClient();
  31. StreamWriter data = new StreamWriter(client.GetStream());
  32. data.Write(@"<element1>data1</element1>
  33. <element2>data3</element2>
  34. <element3>data3</element3>
  35. <element4>data4</element4>");
  36. data.Close();
  37. client.Close();
  38. }
  39. }
  40.  
  41. class Program
  42. {
  43. static void Main(string[] args)
  44. {
  45. //this sets up the server we will be reading
  46. XMLBlaster server = new XMLBlaster();
  47. server.Begin();
  48. //this is the important bit
  49. //First, create the client
  50. TcpClient tcp = new TcpClient(AddressFamily.InterNetwork);
  51. //Next, connect to the server. You probably will want to use the prober settings here
  52. tcp.Connect(IPAddress.Loopback, 12345);
  53. //Since byte manipulation is ugly, let's turn it into strings
  54. StreamReader data_in = new StreamReader(tcp.GetStream());
  55. string content = data_in.ReadToEnd();
  56. //And, just read everything the server has to say
  57. // Console.WriteLine(content);
  58. using (XmlReader reader = XmlReader.Create(new StringReader(content)))
  59. {
  60. reader.ReadToFollowing("element1");
  61. string element1 = reader.ReadElementContentAsString();
  62. reader.ReadToFollowing("element2");
  63. string element2 = reader.ReadElementContentAsString();
  64. reader.ReadToFollowing("element3");
  65. string element3 = reader.ReadElementContentAsString();
  66. reader.ReadToFollowing("element4");
  67. string element4 = reader.ReadElementContentAsString();
  68. System.Data.SqlClient.SqlConnection sqlConnection1 =
  69. new System.Data.SqlClient.SqlConnection("My datasource");
  70. System.Data.SqlClient.SqlCommand cmd = new System.Data.SqlClient.SqlCommand();
  71. cmd.CommandType = System.Data.CommandType.Text;
  72. cmd.CommandText = "My insert SQL-statement";
  73. cmd.Connection = sqlConnection1;
  74. sqlConnection1.Open();
  75. cmd.ExecuteNonQuery();
  76. sqlConnection1.Close();
  77. }
  78. //when we're done, close up shop.
  79. data_in.Close();
  80. tcp.Close();
  81. //this is just to pause the console so you can see what's going on.
  82. //Console.WriteLine("Press any key to continue...");
  83. //Console.ReadKey(false);
  84. }
  85. }
  86. }

Решение задачи: «Получение XML данных по TCP порту»

textual
Листинг программы
  1. using System;
  2. using System.Collections.Generic;
  3. using System.ComponentModel;
  4. using System.Data;
  5. using System.Xml;
  6. using System.Diagnostics;
  7. using System.Linq;
  8. using System.ServiceProcess;
  9. using System.Text;
  10. using System.IO;
  11. using System.Net.Sockets;
  12. using System.Threading;
  13. using System.Net;
  14.  
  15. namespace WindowsService1
  16. {
  17.  
  18.  
  19.     public partial class Service1 : ServiceBase
  20.     {
  21.         public Service1()
  22.         {
  23.             InitializeComponent();
  24.             if (!System.Diagnostics.EventLog.SourceExists("MySource"))
  25.             {
  26.                 System.Diagnostics.EventLog.CreateEventSource(
  27.                     "MySource", "MyNewLog");
  28.             }
  29.             eventLog1.Source = "MySource";
  30.             eventLog1.Log = "MyNewLog";
  31.  
  32.         }
  33.  
  34.         protected override void OnStart(string[] args)
  35.         {
  36.             System.Threading.Thread newThread =
  37.     new System.Threading.Thread(tcpserver);
  38.             newThread.Start();
  39.  
  40.         }
  41.  
  42.         protected override void OnStop()
  43.         {
  44.             eventLog1.WriteEntry("In OnStop");
  45.             TcpListener server = null;
  46.             // Set the TcpListener on port 13000.
  47.             Int32 port = 13000;
  48.             IPAddress localAddr = IPAddress.Parse("127.0.0.1");
  49.  
  50.             // TcpListener server = new TcpListener(port);
  51.             server = new TcpListener(localAddr, port);
  52.  
  53.             // Stop listening for client requests.
  54.             server.Stop();
  55.  
  56.         }
  57.  
  58.         private delegate void tcpDelegate(String data);     // делегат
  59.         private void tcpserver()
  60.     {
  61.         TcpListener server = null;
  62.         try
  63.         {
  64.         // Set the TcpListener on port 13000.
  65.         Int32 port = 13000;
  66.         IPAddress localAddr = IPAddress.Parse("127.0.0.1");
  67.  
  68.         // TcpListener server = new TcpListener(port);
  69.         server = new TcpListener(localAddr, port);
  70.  
  71.         // Start listening for client requests.
  72.         server.Start();
  73.  
  74.         // Buffer for reading data
  75.         Byte[] bytes = new Byte[512];
  76.         String data = null;
  77.  
  78.         // Enter the listening loop.
  79.         while (true)
  80.         {
  81.  
  82.             // Perform a blocking call to accept requests.
  83.             // You could also user server.AcceptSocket() here.
  84.             TcpClient client = server.AcceptTcpClient();
  85.             //Console.WriteLine("Connected!");
  86.  
  87.             data = null;
  88.  
  89.             // Get a stream object for reading and writing
  90.             NetworkStream stream = client.GetStream();
  91.  
  92.             int i;
  93.  
  94.             // Loop to receive all the data sent by the client.
  95.             while ((i = stream.Read(bytes, 0, bytes.Length)) != 0)
  96.             {
  97.                 // Translate data bytes to a ASCII string.
  98.                 data = System.Text.Encoding.ASCII.GetString(bytes, 0, i);
  99.                 tcpDelegate td = InsertIntoBase;
  100.                 IAsyncResult asynchRes = td.BeginInvoke(data, null, null);
  101.                 // Process the data sent by the client.
  102.                 data = data.ToUpper();
  103.                 byte[] msg = System.Text.Encoding.ASCII.GetBytes(data);
  104.                 // Send back a response.
  105.                 stream.Write(msg, 0, msg.Length);
  106.  
  107.             }
  108.  
  109.             // Shutdown and end connection
  110.             client.Close();
  111.         }
  112.         }
  113.         catch (SocketException e)
  114.         {
  115.             Console.WriteLine("SocketException: {0}", e);
  116.         }
  117.     }
  118.  
  119.         static void InsertIntoBase(String data)
  120.         {
  121.             // запись в базу
  122.  
  123.             using (XmlReader reader = XmlReader.Create(new StringReader(data)))
  124.             {
  125.                 reader.ReadToFollowing("element1");
  126.                 string element1 = reader.ReadElementContentAsString();
  127.                 reader.ReadToFollowing("element2");
  128.                 string element2 = reader.ReadElementContentAsString();
  129.                 reader.ReadToFollowing("element3");
  130.                 string element3 = reader.ReadElementContentAsString();
  131.                 reader.ReadToFollowing("element4");
  132.                 string element4 = reader.ReadElementContentAsString();
  133.                 System.Data.SqlClient.SqlConnection sqlConnection1 =
  134.                 new System.Data.SqlClient.SqlConnection("My datasource");
  135.                 System.Data.SqlClient.SqlCommand cmd = new System.Data.SqlClient.SqlCommand();
  136.                 cmd.CommandType = System.Data.CommandType.Text;
  137.                 cmd.CommandText = "My insert SQL-statement";
  138.                 cmd.Connection = sqlConnection1;
  139.                 sqlConnection1.Open();
  140.                 cmd.ExecuteNonQuery();
  141.                 sqlConnection1.Close();
  142.  
  143.             }
  144.         }
  145.  
  146.     }
  147.  
  148. }

ИИ поможет Вам:


  • решить любую задачу по программированию
  • объяснить код
  • расставить комментарии в коде
  • и т.д
Попробуйте бесплатно

Оцени полезность:

10   голосов , оценка 3.6 из 5

Нужна аналогичная работа?

Оформи быстрый заказ и узнай стоимость

Бесплатно
Оформите заказ и авторы начнут откликаться уже через 10 минут