Sending XML over a Socket connection
-
Dear all, Im very new in this, hope to get some tips. I have to send some data in XML over a Socket connection to a application that opens a TCP/IP port and acts as a server. I found some samples on google like this one : http://www.java2s.com/Tutorial/CSharp/0580\_\_Network/SimpleTcpClientsenddatatotheserver.htm But what is the best way to achieve this? Thanks in advance.
-
Dear all, Im very new in this, hope to get some tips. I have to send some data in XML over a Socket connection to a application that opens a TCP/IP port and acts as a server. I found some samples on google like this one : http://www.java2s.com/Tutorial/CSharp/0580\_\_Network/SimpleTcpClientsenddatatotheserver.htm But what is the best way to achieve this? Thanks in advance.
Find below code for the same.
XDocument doc = XDocument.Parse("<Hello>World</Hello>", LoadOptions.PreserveWhitespace);
string host = "localhost";
int port = 1234;// Look up the address for the specified host. IPHostEntry address = Dns.GetHostEntry(host); IPEndPoint ipe = new IPEndPoint(address.AddressList\[0\], port); // Create Socket. using (Socket sock = new Socket(ipe.AddressFamily, SocketType.Stream, ProtocolType.Tcp)) { sock.Connect(ipe); // Connect to the Socket. // Create Stream. using (NetworkStream sockStream = new NetworkStream(sock)) { // Read from the XDocument. using (XmlReader reader = doc.CreateReader()) { // Copy nodes to an XmlWriter which transforms them to bytes that are written to the Stream for the Socket. XmlWriterSettings settings = new XmlWriterSettings(); settings.Encoding = new UTF8Encoding(false, true); using (XmlWriter writer = XmlWriter.Create(sockStream, settings)) { while (reader.Read()) // While there is another XML node... { writer.WriteNode(reader, false); // Copy that node. } } } } }
For more information find following links useful. File Transfer using Socket Application in C# .NET 2.0[^] http://social.msdn.microsoft.com/Forums/en/ncl/thread/6994d38b-5caf-47ff-a425-969651d1a292[^] HTH
Jinal Desai - LIVE Experience is mother of sage....