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
Data-BaseAsked:
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

dericstoneCommented:
Sure that example is a good start. 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.

Here's how to make the server keep running. The attached code is only a sample to get you going.

Hope that helps!
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 = System.Text.ASCIIEncoding.ASCII.GetString(b);
  if (cmd.Contains("CLOSE-CONNECTION"))
    break;
  ASCIIEncoding asen=new ASCIIEncoding();
  s.Send(asen.GetBytes("The string was recieved by the server."));
  Console.WriteLine("\nSent Acknowledgement");
}

Open in new window

0

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
Data-BaseAuthor Commented:
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
0
Data-BaseAuthor Commented:
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

0
Cloud Class® Course: Certified Penetration Testing

This CPTE Certified Penetration Testing Engineer course covers everything you need to know about becoming a Certified Penetration Testing Engineer. Career Path: Professional roles include Ethical Hackers, Security Consultants, System Administrators, and Chief Security Officers.

dericstoneCommented:
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.
0
Data-BaseAuthor Commented:
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 !!!
0
Data-BaseAuthor Commented:
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

0
dericstoneCommented:
This is unrelated to the original question. Please start a new topic. Thanks.
0
Data-BaseAuthor Commented:
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
0
dericstoneCommented:
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"?
0
Data-BaseAuthor Commented:
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
0
dericstoneCommented:
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.
0
Data-BaseAuthor Commented:
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
0
Data-BaseAuthor Commented:
Thank you for your time and help
0
dericstoneCommented:
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

0
Data-BaseAuthor Commented:
aha now I get you :-)

Thank allot
0
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
.NET Programming

From novice to tech pro — start learning today.

Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.