I am trying to convert an object to byte array & send it through socket to other process
but process stops while deserialization of object it simply hangs.
what is wrong with code ?
client code
namespace client_2
{
[Serializable]
class data
{
public ArrayList list;
public data()
{
list = new ArrayList();
}
public void add(object o)
{
list.Add(o);
}
public void disp()
{
foreach (object ob in list)
{
Console.WriteLine(ob.ToString());
}
}
}
class Program
{
static void Main(string[] args)
{
IPAddress adr = IPAddress.Parse("127.0.0.1");
TcpClient cli = new TcpClient();
cli.Connect(adr, 5577);
NetworkStream strem = cli.GetStream();
if (cli.Connected)
{
data d = new data();
d.add("hello");
d.add(44);
Byte[] buffer = new Byte[1024];
BinaryFormatter from = new BinaryFormatter();
MemoryStream ms = new MemoryStream(buffer,true);
from.Serialize(ms, d);
strem.Write(buffer, 0, buffer.Length);
}
strem.Close();
cli.Close();
}
}
}
server code
namespace server_2
{
[Serializable]
class data
{
public ArrayList list;
public data()
{
list = new ArrayList();
}
public void add(object o)
{
list.Add(o);
}
public void disp()
{
foreach (object ob in list)
{
Console.WriteLine(ob.ToString());
}
}
}
class Program
{
public static void handleReq(object o)
{
TcpClient client = o as TcpClient;
NetworkStream strm = client.GetStream();
Byte[] buf = new Byte[1024];
strm.Read(buf, 0, 1024);
BinaryFormatter from = new BinaryFormatter();
MemoryStream ms = new MemoryStream(buf, true);
data d = (data)from.Deserialize(ms); // hangs here
d.disp();
strm.Close();
client.Close();
}
static void Main(string[] args)
{
IPAddress addr = IPAddress.Parse("127.0.0.1");
TcpListener listner = new TcpListener(addr,5577); ;
listner.Start();
while (true)
{
TcpClient client = listner.AcceptTcpClient();
Task.Factory.StartNew(handleReq,client);
}
listner.Stop();
}
}
}
You need to read the whole networkstream not just 1024 bytes. You can put the networkstream directly in the Deserialize.
It will fail anyhow because the class
dataon the serverside doesn’t match the classdataon the client side (use a shared dll for client and server that holds the classdata)