views:

281

answers:

2

Hello,

I'm working on a server/client project the client will be asking the server for info and the server will send them back to the client

the info may be string,number, array, list, arraylist or any other object

I found allot of examples but I faced issues!!!!

the solution I found so far is to serialize the object (data) and send it then de-serialize it to process

here is the server code

public void RunServer(string SrvIP,int SrvPort)
    {
        try
        {
            var ipAd = IPAddress.Parse(SrvIP);


            /* Initializes the Listener */
            if (ipAd != null)
            {
                var myList = new TcpListener(ipAd, SrvPort);

                /* Start Listeneting at the specified port */
                myList.Start();

                Console.WriteLine("The server is running at port "+SrvPort+"...");
                Console.WriteLine("The local End point is  :" + myList.LocalEndpoint);
                Console.WriteLine("Waiting for a connection.....");


                while (true)
                {
                    Socket s = myList.AcceptSocket();
                    Console.WriteLine("Connection accepted from " + s.RemoteEndPoint);

                    var b = new byte[100];
                    int k = s.Receive(b);
                    Console.WriteLine("Recieved...");
                    for (int i = 0; i < k; i++)
                        Console.Write(Convert.ToChar(b[i]));
                    string cmd = Encoding.ASCII.GetString(b);
                    if (cmd.Contains("CLOSE-CONNECTION"))
                        break;
                    var asen = new ASCIIEncoding();

                    // sending text 
                    s.Send(asen.GetBytes("The string was received by the server."));

                    // the line bove to be modified to send serialized object?


                    Console.WriteLine("\nSent Acknowledgement");
                    s.Close();
                    Console.ReadLine();
                }
                /* clean up */

                myList.Stop();
            }
        }
        catch (Exception e)
        {
            Console.WriteLine("Error..... " + e.StackTrace);
        }
    }

here is the client code that should return an object

public object runClient(string SrvIP, int SrvPort)
        {
            object obj = null;
            try
            {
                var tcpclnt = new TcpClient();
                Console.WriteLine("Connecting.....");

                tcpclnt.Connect(SrvIP, SrvPort);
                // use the ipaddress as in the server program


                Console.WriteLine("Connected");
                Console.Write("Enter the string to be transmitted : ");

                var str = Console.ReadLine();
                Stream stm = tcpclnt.GetStream();

                var asen = new ASCIIEncoding();
                if (str != null)
                {
                    var ba = asen.GetBytes(str);
                    Console.WriteLine("Transmitting.....");

                    stm.Write(ba, 0, ba.Length);
                }

                var bb = new byte[2000];

                var k = stm.Read(bb, 0, bb.Length);

                string data = null;

                for (var i = 0; i < k; i++)
                    Console.Write(Convert.ToChar(bb[i]));

                //convert to object code ??????

                Console.ReadLine();

                tcpclnt.Close();
            }

            catch (Exception e)
            {
                Console.WriteLine("Error..... " + e.StackTrace);
            }

            return obj;

        }

I need to know a good serialize/serialize and how to integrate it into the solution above :-(

I would be really thankful for any help

cheers

A: 

You could serialize your objects into json, using JavaScriptSerializer.. It's very lightweight, and easy to use. Just don't forget to add a reference to System.Web.Extensions.dll

e.g.:

var js = new JavaScriptSerializer();
var data = js.Deserialize<MyClass>(receivedString);

and in the other class

var js = new JavaScriptSerializer();
var serializedData = js.Serialize(dataObject);
Artiom Chilaru
+1  A: 

Hi,

have you considered using Windows Communication Foundation services? WCF gives you extensible API which supports the most common protocols out of the box. And what is more WCF has built in serialization/deserialization.

If you do don't want to use WCF then you can use Binary Serialization.

This is a sample usage of the binary serialization:

private Stream SerializeMultipleObjects()
{ 
    // Initialize a storage medium to hold the serialized object
    Stream stream = new MemoryStream();

    // Serialize an object into the storage medium referenced by 'stream' object.
    BinaryFormatter formatter = new BinaryFormatter();

    // Serialize multiple objects into the stream
    formatter.Serialize( stream, obOrders );
    formatter.Serialize( stream, obProducts );
    formatter.Serialize( stream, obCustomers );

    // Return a stream with multiple objects
    return stream; 
}

private void DeSerializeMultipleObject(Stream stream)
{
    // Construct a binary formatter
    BinaryFormatter formatter = new BinaryFormatter();

    // Deserialize the stream into object
    Orders     obOrders    = (Orders)formatter.Deserialize( stream );
    Products   obProducts  = (Products)formatter.Deserialize( stream );
    Customers  obCustomers = (Customer)formatter.Deserialize( stream );
}

Here is the entire article about binary serialization.

-Pavel

Pavel Nikolov
Thanks allot :-)well I'm new to all thisI do not care what way to go to achieve and learn what I needall I need is a serve/client solution that help me to send values/objects to the server and get results/answres from the serverlike sending a command (string) "getProcesses"and the server will send back an array or an object (Process[] processlist = Process.GetProcesses();) back to the clientis that to hard? what what is the best way to do it?
Data-Base
but how to use your code with my code?
Data-Base
I'd recommend you to read one of the available "Getting started with WCF" tutorials like:http://msdn.microsoft.com/en-us/library/ms734712(VS.100).aspxhttp://weblogs.asp.net/ralfw/archive/2007/04/14/a-truely-simple-example-to-get-started-with-wcf.aspxhttp://msdn.microsoft.com/en-us/library/ms730144.aspx
Pavel Nikolov
Usually you wouldn't serialize/deserialize the objects yourself - WCF does it for you.
Pavel Nikolov