locked
Client Server Code RRS feed

  • Question

  •  Hi,

    I have the following code running fine. In this code, a server sends multiple data to different clients at port 4500.

    However the server is not able to recognize the clients. So I want to pass the ClientID from the client itself. Something like the client saying to the server "I am Client1 and I want my data" or Client 2 saying that it wants data for Client2. So this way, if someone is viewing data of Client1 sitting at two different locations, he/she is able to view the 'same' data. Currently with the code i have posted below, this is not possible. The server just sends different data to different clients. How can I do this?

    SERVER CODE

    namespace MyServer
    {
        class Program
        {
            static void Main(string[] args)
            {
                MySockets server = new MySockets();
                server.StartMyServer();
                Console.Read();
            }
        }
    }


    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Net;
    using System.Net.Sockets;
    using System.IO;
    using System.Timers;
    using System.Xml;
    using System.Reflection;
    using System.Threading;
    using System.Runtime.Remoting.Messaging;

    namespace MyServer
    {
        public class MySockets
        {
            TcpListener tcpListener = null;
            static ManualResetEvent tcpClientConn = new ManualResetEvent(false);
            List<StreamWriter> stream = new List<StreamWriter>();
            public TcpClient client;
            delegate void DataSender(MySockets inst);


            // Start the Socket Server
            public void StartMyServer()
            {
                try
                {
                    tcpListener = new TcpListener(IPAddress.Parse("127.0.0.1"), 4500);
                    tcpListener.Start();
                    Console.WriteLine("Server Started..");
                    while (true)
                    {
                        tcpClientConn.Reset();
                        Console.WriteLine("Waiting for FMClients to connect...");
                        client = tcpListener.AcceptTcpClient();
                        MyValuesGenerator gen = new MyValuesGenerator();
                        DataSender ds = new DataSender(gen.SendData);

                        ds.BeginInvoke(this, new AsyncCallback(AfterDataSend), this);

                    }
                }
                catch (Exception startFMEx)
                {
                    CatchError(startFMEx);
                }
            }

            static void AfterDataSend(IAsyncResult ar)
            {
                AsyncResult res = (AsyncResult)ar;
                DataSender ds = res.AsyncDelegate as DataSender;
                ds.EndInvoke(ar);
            }

            // Stop the Socket Server
            public void StopMyServer()
            {
                foreach (StreamWriter writer in stream)
                {
                    writer.Dispose();
                }
                stream.Clear();
                tcpListener.Stop();
                tcpListener = null;
            }



            private void CatchError(Exception ex)
            {
                string appPath = Assembly.GetCallingAssembly().Location;
                string logFilePath = appPath.Substring(0, appPath.LastIndexOf("\\")) + ".log";
                StreamWriter writer = new StreamWriter(logFilePath, true);
                try
                {
                    writer.WriteLine(logFilePath,
                        String.Format("There was an error in MySockets: {0} \r\n StackTrace: {1}", ex.Message, ex.StackTrace));
                }
                catch { }
                finally
                {
                    writer.Close();
                }
            }
        }

        public class MyValuesGenerator
        {
            System.Timers.Timer timer = null;
            //static ManualResetEvent tcpClientConn = new ManualResetEvent(false);
            List<StreamWriter> stream = new List<StreamWriter>();
            //int seconds;
            static int maxValue;
            static int minValue;
            static double interval;
            public static int cCount;
            MyServer.MySockets server = null;


            public void InitializeValues()
            {
                //seconds = 1;
                minValue = 60;
                maxValue = 90;
                interval = 1000D;
                cCount = 1;
            }

            public void SendData(MySockets inst)
            {
                if (cCount < 1)
                    this.InitializeValues();
                else
                    cCount++;
                timer = new System.Timers.Timer();
                timer.Enabled = false;
                timer.Interval = interval;
                timer.Elapsed += new ElapsedEventHandler(_Timer_Elapsed);
                //MyServer.MySockets server = inst;
                server = inst;

                if (server.client.Connected)
                {
                    Console.WriteLine("Client " + cCount + " connected...");
                    StreamWriter writer = new StreamWriter(server.client.GetStream());
                    writer.AutoFlush = true;
                    stream.Add(writer);
                    writer.WriteLine(GetDeviceData());

                    if (timer.Enabled == false)
                    {
                        timer.Start();
                    }
                }
            }

            private string GetDeviceData()
            {
                // To omit the <?xml version="1.0" encoding="utf-16"?>
                XmlWriterSettings writerSettings = new XmlWriterSettings();
                writerSettings.OmitXmlDeclaration = true;

                StringWriter sw = new StringWriter();
                using (XmlWriter writer = XmlWriter.Create(sw, writerSettings))
                {
                    string strClient = "Bed" + cCount;
                    writer.WriteStartElement("v");    
                    writer.WriteAttributeString("ClientID", strClient);

                    Random randNum = new Random(System.DateTime.Now.Millisecond);
                    int num = randNum.Next(minValue, maxValue);
                    string sampleData = num + " " + num + " " + num + " " + num;
                    writer.WriteString(sampleData);
                    writer.WriteEndElement();
                }
                return sw.ToString();
            }

            private void _Timer_Elapsed(object sender, ElapsedEventArgs e)
            {
                SendPackets(GetDeviceData());
            }

            private void SendPackets(string liveData)
            {
                try
                {
                    if (stream != null)
                    {
                        foreach (StreamWriter writer in stream)
                        {
                            if (writer != null)
                            {
                                writer.Write(liveData);
                            }
                        }
                    }
                }
                catch (Exception x)
                {
                    CatchError(x);
                }
            }

            private void CatchError(Exception ex)
            {
                string appPath = Assembly.GetCallingAssembly().Location;
                string logFilePath = appPath.Substring(0, appPath.LastIndexOf("\\")) + ".log";
                StreamWriter writer = new StreamWriter(logFilePath, true);
                try
                {
                    writer.WriteLine(logFilePath,
                        String.Format("There was an error in MySockets: {0} \r\n StackTrace: {1}", ex.Message, ex.StackTrace));
                }
                catch { }
                finally
                {
                    writer.Close();
                }
            }

        }


    }


    CLIENT CODE



    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.IO;
    using System.Net;
    using System.Net.Sockets;

    namespace MyClients
    {
        class Program
        {
            static void Main(string[] args)
            {
                TcpClient tcpCl = new TcpClient();
                    IPEndPoint endPoint =
                       new IPEndPoint(IPAddress.Parse("127.0.0.1"), 4500);
                    tcpCl.Connect(endPoint);          

                NetworkStream ns = tcpCl.GetStream();
                StreamReader sReader = new StreamReader(ns);
                while (true)
                {
                    try
                    {
                        char[] charArr = new char[64];
                        int i = 0;
                        while ((i = sReader.Read(charArr, 0, 64)) > 0)
                        {
                            string str = new String(charArr, 0, i);
                            Console.WriteLine(str);
                        }
                    }
                    catch (Exception exp)
                    {
                        Console.WriteLine(exp.Message);
                        break;
                    }
                }
                Console.Read();
            }
     
        }
    }

    Thanks.

    • Moved by jack 321 Friday, June 13, 2008 7:24 AM duplicate post
    Wednesday, June 11, 2008 2:11 PM

Answers

  • duplicate post
    http://forums.msdn.microsoft.com/en/csharpgeneral/thread/9ca2755d-8601-43b9-bc99-fe0b7c2f0bd9/


    Please remember to mark the replies as answers if they help and unmark them if they provide no help.
    Friday, June 13, 2008 7:23 AM

All replies

  • duplicate post
    http://forums.msdn.microsoft.com/en/csharpgeneral/thread/9ca2755d-8601-43b9-bc99-fe0b7c2f0bd9/


    Please remember to mark the replies as answers if they help and unmark them if they provide no help.
    Friday, June 13, 2008 7:23 AM
  • This was moved to the Off Topic forum. I can move it to a specific forum for you, if you'd like.

    Thanks!


    Ed Price (a.k.a User Ed), SQL Server Experience Program Manager (Blog, Twitter, Wiki)

    Thursday, May 10, 2012 6:50 AM