array of strings is not getting displayed

SK33

New member
Joined
Sep 26, 2015
Messages
4
Programming Experience
Beginner
I have written a simple server code in c# which sends a string array to the client and the client receives it and displays it on the console. But in my code, the client is not getting the string array, so it is not being displayed on the console. Is there anything wrong in the code?
// **Client Side:**


    using System;
    using System.Collections.Generic;
    using System.Net;
    using System.Net.Sockets;
    using System.IO;
    using System.Text;
    using System.Xml.Serialization;
    
    namespace Client
    {
        class Program
        {
            static void Main(string[] args)
            {
                try
                {
                    byte[] data = new byte[1024];
                              
                    TcpClient tcpClient = new TcpClient("127.0.0.1", 1234);
                    NetworkStream ns = tcpClient.GetStream();             
    
                    var serializer = new XmlSerializer(typeof(string[]));
                    var stringArray = (string[])serializer.Deserialize(tcpClient.GetStream());  
                  
                    foreach (string s in stringArray)  //displaying the string array
                    {
                        Console.WriteLine(s);
                    }
    
                }
                catch (Exception e)
                {
                    Console.Write(e.Message);
                }
    
                Console.Read();
            }
        }
    }




// **Server Side:**


    using System;
    using System.Collections.Generic;
    using System.Net;
    using System.Net.Sockets;
    using System.IO;
    using System.Text;
    using System.Xml.Serialization;


    namespace server
    {
        class Program
        {
            static void Main(string[] args)
            {  
                TcpListener tcpListener = new TcpListener(IPAddress.Any, 1234);
                tcpListener.Start();  


                while (true)
                {                     
                    TcpClient tcpClient = tcpListener.AcceptTcpClient();
                    NetworkStream ns = tcpClient.GetStream();
                    string[] array1 = new string[] { "abc", "def", "xyz" };


                    var serializer = new XmlSerializer(typeof(string[]));
                    serializer.Serialize(tcpClient.GetStream(), array1);
              
                }               
            }
        }
    }

**Which correction will I have to make in the code?**
 

JohnH

C# Forum Moderator
Staff member
Joined
Apr 23, 2011
Messages
1,209
Location
Norway
Programming Experience
10+
Call ns.Close and tcpClient.Close in server after finished serializing document, same in client after deserializing it.
 
Top Bottom