Link to home
Start Free TrialLog in
Avatar of Data-Base
Data-BaseFlag for Norway

asked on

c# server (simple! maybe?)

Hello,

I'm looking for a way to do the following:

create a simple server/client

the server will be running as a service (that is simple)
the client will send the server "commands" (it can be text,number or array/list)
the server receive it then run a method and send the results of the method back to the client (as text, number or array/list)

the server will have few methods and will run any method based on the "command" that it receives from the client!

now this is new task for me I never worked with Server/client "thing" and i'm new to programming (I used to do some things as a hubby) but I think i'm a fast learner ;-)

I found a nice example on http://www.c-sharpcorner.com/uploadfile/sthangaraju/tcpclientserverst11182005014316am/tcpclientserverst.aspx

1- is it good to use it as a based to build what I want? if not which approach I should take?
2- how to make the server keep running not exit after the client send the text?


cheers
ASKER CERTIFIED SOLUTION
Avatar of dericstone
dericstone
Flag of Germany image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of Data-Base

ASKER

nice thanks allot,

The part that seems most lacking is a protocol to indicate the beginning  of a command, end of a command, how to handle any response, etc. You  will need to design this according to what you need.
do you have an example?

as I wrote above it will be just strings/number or list

is it hard to make it send any object type? I can imagine the size is the limitation? is there more.

I'm totally blank in this area :-)


cheers
I just tested your code.

the program stops when the client exits !!!

here is my full code
using System;
using System.Net;
using System.Net.Sockets;
using System.Text;

namespace textSystemServerConsole
{
    class Program
    {
        static void Main(string[] args)
        {
            RunServer();
        }

        //================================================================
        private static void RunServer()
        {
            try
            {
                var ipAd = IPAddress.Parse("192.168.1.1");
                // use local m/c IP address, and 

                // use the same in the client


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

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

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

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

                    var b = new byte[100];
                    while (true)
                    {
                        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();
                        s.Send(asen.GetBytes("The string was recieved by the server."));
                        Console.WriteLine("\nSent Acknowledgement");
                    }
                    /* clean up */
                    s.Close();
                    myList.Stop();
                }
            }
            catch (Exception e)
            {
                Console.WriteLine("Error..... " + e.StackTrace);
            }
        }
        //================================================================
    }
}

Open in new window

Here's an idea for a protocol:
http://srcpd.sourceforge.net/srcp/srcp-083.pdf

To keep the server alive you will need to put the socket connection and disconnection inside the loop. What is happening now is the Receive method is throwing an exception when the client disconnects. You should catch this exception, and then go back to waiting for a new connection.

That brings up an interesting question: Will you need to handle multiple connections? If so, don't forget about it -- the code will need to be modified to handle that, too.
hello,

thanks allot, now the server is up all time :-)

the protocol thing is still tricky for me, any easier way?
I do not want to re-invent the wheel !!!
Hi,

I found the methods (attached below), I tried to use it with server client code but I'm facing some issues !!

how to integrate it and make it work?
//================================================================
        public byte[] ObjectToByteArray(Object obj)
        {
            if (obj == null)
                return null;
            var bf = new BinaryFormatter();
            var ms = new MemoryStream();
            bf.Serialize(ms, obj);
            return ms.ToArray();
        }
        // Convert a byte array to an Object
        //================================================================
        public Object ByteArrayToObject(byte[] arrBytes)
        {
            var memStream = new MemoryStream();
            var binForm = new BinaryFormatter();
            memStream.Write(arrBytes, 0, arrBytes.Length);
            memStream.Seek(0, SeekOrigin.Begin);
            var obj = (Object)binForm.Deserialize(memStream);
            return obj;
        }
        //================================================================

Open in new window

This is unrelated to the original question. Please start a new topic. Thanks.
hi,

thank you for your replay

i wrote above

the server receive it then run a method and send the results of the method back to the client (as text, number or array/list)

I believe it is related :-)

if you think it is not, then I will take your word for it :-)

thank you again
OK now I see how it is related. Client should use ObjectToByteArray() and server should use ByteArrayToObject(). Seems straight forward. You said, "I tried to use it with server client code but I'm facing some issues !!" Perhaps you could describe your "issues"?
my issues that I do not fully understand all of that

I'm reading to understand, but do not have that much time (mainly I'm a system admin and not a programmer)

so I'm not sure how to make the client or the server utilizes the objecttobytearray or bytearraytoobject method so I can send some data!

so I do really appreciate your help :-)


cheers
sorry but this is where I have to stop. I really don't understand how you know you should use these methods, but then you don't know how to use them?!?! It takes some knowledge of the problem to understand that you need these methods... To me, using the methods is the easier part. If I explain how to use these methods, I might as well write the whole application for you. Since I'm not going to do that...well I need to stop here. Good luck.
Hello,
for sure I do not want you to write the application for me! I will miss all the fun ;-)
beside this part is just a small part of the whole system, but kind of essential


when I look at how the server send the data I find my self looking at this part for example

var asen = new ASCIIEncoding();
s.Send(asen.GetBytes("The string was recieved by the server."));
Console.WriteLine("\nSent Acknowledgement");

so what I did I replace this part with

var asen = new ASCIIEncoding();
s.Send(ObjectToByteArray("The string was recieved by the server."));
Console.WriteLine("\nSent Acknowledgement");

I know I'm making something wrong here, but not sure what exactly

any why, thanks allot for your time and help
Thank you for your time and help
Try making a class with a string inside it. Then send an object of the class.

The other end will also need to know how the class is defined, and use that to extract the string.

Thanks for the points. Good luck!
class MyString
{
  string msg;
}
...
MyString myCoolString = new MyString();
myCoolString.msg = "The string was recieved by the server.";
var asen = new ASCIIEncoding();
s.Send(ObjectToByteArray(myCoolString));
Console.WriteLine("\nSent Acknowledgement");

Open in new window

aha now I get you :-)

Thank allot