Получение XML данных по TCP порту - C#
Формулировка задачи:
Здравствуйте,
Пишу приложение, которое будет получать XML-данные по TCP, а затем писать эти данные в базу данных.
Нашёл в интернете пример как отправлять и принимать XML по TCP-порту. Использовал его в своём приложении. XML отправляется, принимается, парсится и пишется в базу только, если прописать сам XML-код в тексте программы. А надо, чтобы программа открывала соединение на указанном порту и прослушивала этот порт, ожидая XML-сообщения от любого приложения (например отправки сообщения по телнету), а затем писала бы это сообщение в базу. Вопрос, как это сделать? Можете ли привести пример кода? Или дать ссылку на реализацию подобной программы. C# знаю слабо, поэтому желательны примеры кода
Отправляю то что пока у меня получилось. Спасибо!
Листинг программы
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Text;
- using System.Net;
- using System.IO;
- using System.Net.Sockets;
- using System.Threading;
- using System.Xml;
- namespace ConsoleApplication2
- {
- class XMLBlaster
- {
- Thread myThread;
- public XMLBlaster()
- {
- myThread = new Thread(Start);
- }
- public void Begin()
- {
- myThread.Start();
- }
- //This will listen for a connection on port 12345, and send a tiny XML document
- //to the first person to connect.
- protected void Start()
- {
- TcpListener tcp = new TcpListener(IPAddress.Any, 12345);
- tcp.Start(1);
- TcpClient client = tcp.AcceptTcpClient();
- StreamWriter data = new StreamWriter(client.GetStream());
- data.Write(@"<element1>data1</element1>
- <element2>data3</element2>
- <element3>data3</element3>
- <element4>data4</element4>");
- data.Close();
- client.Close();
- }
- }
- class Program
- {
- static void Main(string[] args)
- {
- //this sets up the server we will be reading
- XMLBlaster server = new XMLBlaster();
- server.Begin();
- //this is the important bit
- //First, create the client
- TcpClient tcp = new TcpClient(AddressFamily.InterNetwork);
- //Next, connect to the server. You probably will want to use the prober settings here
- tcp.Connect(IPAddress.Loopback, 12345);
- //Since byte manipulation is ugly, let's turn it into strings
- StreamReader data_in = new StreamReader(tcp.GetStream());
- string content = data_in.ReadToEnd();
- //And, just read everything the server has to say
- // Console.WriteLine(content);
- using (XmlReader reader = XmlReader.Create(new StringReader(content)))
- {
- reader.ReadToFollowing("element1");
- string element1 = reader.ReadElementContentAsString();
- reader.ReadToFollowing("element2");
- string element2 = reader.ReadElementContentAsString();
- reader.ReadToFollowing("element3");
- string element3 = reader.ReadElementContentAsString();
- reader.ReadToFollowing("element4");
- string element4 = reader.ReadElementContentAsString();
- System.Data.SqlClient.SqlConnection sqlConnection1 =
- new System.Data.SqlClient.SqlConnection("My datasource");
- System.Data.SqlClient.SqlCommand cmd = new System.Data.SqlClient.SqlCommand();
- cmd.CommandType = System.Data.CommandType.Text;
- cmd.CommandText = "My insert SQL-statement";
- cmd.Connection = sqlConnection1;
- sqlConnection1.Open();
- cmd.ExecuteNonQuery();
- sqlConnection1.Close();
- }
- //when we're done, close up shop.
- data_in.Close();
- tcp.Close();
- //this is just to pause the console so you can see what's going on.
- //Console.WriteLine("Press any key to continue...");
- //Console.ReadKey(false);
- }
- }
- }
Решение задачи: «Получение XML данных по TCP порту»
textual
Листинг программы
- using System;
- using System.Collections.Generic;
- using System.ComponentModel;
- using System.Data;
- using System.Xml;
- using System.Diagnostics;
- using System.Linq;
- using System.ServiceProcess;
- using System.Text;
- using System.IO;
- using System.Net.Sockets;
- using System.Threading;
- using System.Net;
- namespace WindowsService1
- {
- public partial class Service1 : ServiceBase
- {
- public Service1()
- {
- InitializeComponent();
- if (!System.Diagnostics.EventLog.SourceExists("MySource"))
- {
- System.Diagnostics.EventLog.CreateEventSource(
- "MySource", "MyNewLog");
- }
- eventLog1.Source = "MySource";
- eventLog1.Log = "MyNewLog";
- }
- protected override void OnStart(string[] args)
- {
- System.Threading.Thread newThread =
- new System.Threading.Thread(tcpserver);
- newThread.Start();
- }
- protected override void OnStop()
- {
- eventLog1.WriteEntry("In OnStop");
- TcpListener server = null;
- // 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);
- // Stop listening for client requests.
- server.Stop();
- }
- private delegate void tcpDelegate(String data); // делегат
- private void tcpserver()
- {
- 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[512];
- String data = null;
- // Enter the listening loop.
- while (true)
- {
- // Perform a blocking call to accept requests.
- // You could also user 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 = System.Text.Encoding.ASCII.GetString(bytes, 0, i);
- tcpDelegate td = InsertIntoBase;
- IAsyncResult asynchRes = td.BeginInvoke(data, null, null);
- // Process the data sent by the client.
- data = data.ToUpper();
- byte[] msg = System.Text.Encoding.ASCII.GetBytes(data);
- // Send back a response.
- stream.Write(msg, 0, msg.Length);
- }
- // Shutdown and end connection
- client.Close();
- }
- }
- catch (SocketException e)
- {
- Console.WriteLine("SocketException: {0}", e);
- }
- }
- static void InsertIntoBase(String data)
- {
- // запись в базу
- using (XmlReader reader = XmlReader.Create(new StringReader(data)))
- {
- reader.ReadToFollowing("element1");
- string element1 = reader.ReadElementContentAsString();
- reader.ReadToFollowing("element2");
- string element2 = reader.ReadElementContentAsString();
- reader.ReadToFollowing("element3");
- string element3 = reader.ReadElementContentAsString();
- reader.ReadToFollowing("element4");
- string element4 = reader.ReadElementContentAsString();
- System.Data.SqlClient.SqlConnection sqlConnection1 =
- new System.Data.SqlClient.SqlConnection("My datasource");
- System.Data.SqlClient.SqlCommand cmd = new System.Data.SqlClient.SqlCommand();
- cmd.CommandType = System.Data.CommandType.Text;
- cmd.CommandText = "My insert SQL-statement";
- cmd.Connection = sqlConnection1;
- sqlConnection1.Open();
- cmd.ExecuteNonQuery();
- sqlConnection1.Close();
- }
- }
- }
- }
ИИ поможет Вам:
- решить любую задачу по программированию
- объяснить код
- расставить комментарии в коде
- и т.д