C # array of strings not showing

The following is a simple segment of server and client code written in C #. I want to send a string array from the server and get it from the end of the client and display it on the console. But the array of strings is not displayed. Is there something wrong in the code?

Server

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(); byte[] data = new byte[1024]; NetworkStream ns = tcpClient.GetStream(); string[] arr1 = new string[] { "one", "two", "three" }; var serializer = new XmlSerializer(typeof(string[])); serializer.Serialize(tcpClient.GetStream(), arr1); int recv = ns.Read(data, 0, data.Length); string id = Encoding.ASCII.GetString(data, 0, recv); Console.WriteLine(id); } } } } 

Client

 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]; string stringData; TcpClient tcpClient = new TcpClient("127.0.0.1", 1234); NetworkStream ns = tcpClient.GetStream(); var serializer = new XmlSerializer(typeof(string[])); var stringArr = (string[])serializer.Deserialize(tcpClient.GetStream()); foreach (string s in stringArr) { Console.WriteLine(s); } string input = Console.ReadLine(); ns.Write(Encoding.ASCII.GetBytes(input), 0, input.Length); ns.Flush(); } catch (Exception e) { Console.Write(e.Message); } Console.Read(); } } } 
+5
source share
1 answer

I ran your code and hung it in this line on the client

 var stringArr = (string[])serializer.Deserialize(tcpClient.GetStream()); 

Then I changed it to first read from NetworkStream into a byte array, and then use MemoryStream I, a deserialized byte array. Then it worked as I expected.

So this could be a problem using NetworkStream with deserialization.

XmlSerializer.Deserialize blocks through NetworkStream

Looking at this question in Stackoverflow, it seems that the XmlSerializer will continue to attempt to read from Stream until it reaches the end, which will cause your problem.

To fix, do as suggested, and read the data you want to deserialize into an array of bytes.

+3
source

Source: https://habr.com/ru/post/1232428/


All Articles