Click here to Skip to main content
15,902,896 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Here's the code I've got so far. It is working and can receive objects. However I want to send the object I get back out to all connected clients. I'm guessing I would need an arraylist of some sort to store the connected clients. How do I do this?

My current code:
C#
class TcpServer
    {
        private TcpListener _server;
        private Boolean _isRunning;

        public TcpServer(int port)
        {
            _server = new TcpListener(IPAddress.Any, port);
            _server.Start();

            _isRunning = true;

            LoopClients();
        }

        public void LoopClients()
        {
            while (_isRunning)
            {
                // wait for client connection
                TcpClient newClient = _server.AcceptTcpClient();
                // client found.
                // create a thread to handle communication
                Thread t = new Thread(new ParameterizedThreadStart(HandleClient));
                t.Start(newClient);
            }
        }

        public void HandleClient(object obj)
        {
            // retrieve client from parameter passed to thread
            TcpClient client = (TcpClient)obj;
            // sets two streams
            StreamWriter sWriter = new StreamWriter(client.GetStream(), Encoding.ASCII);
            StreamReader sReader = new StreamReader(client.GetStream(), Encoding.ASCII);
            // you could use the NetworkStream to read and write, 
            // but there is no forcing flush, even when requested
            Boolean bClientConnected = true;
            Person p = null;
            while (bClientConnected)
            {
                try
                {
                    // reads from stream
                    //Here if I wanted I could get the object back
                    //But I want to send this object back out to all clients
                    //NetworkStream strm = client.GetStream();
                    //IFormatter formatter = new BinaryFormatter();
                    //p = (Person)formatter.Deserialize(strm); // you have to cast the deserialized object
                    //strm.Close();
                    // shows content on the console.
                    //Console.WriteLine("New person object: First name > " + p.FirstName);
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.Message);
                }
               
            }
        }
    }
Posted

1 solution

Yes, you need to store the connected clients. For example, it could be the instances of TcpClient obtained as a result of a call to System.IO.Sockets.TcpListener.AcceptTcpClient or instances Socket obtained as a result of a call to System.IO.Sockets.TcpListener.AcceptSocket:
http://msdn.microsoft.com/en-us/library/vstudio/system.net.sockets.tcplistener.accepttcpclient[^],
http://msdn.microsoft.com/en-us/library/vstudio/system.net.sockets.tcplistener.acceptsocket[^].

You could have two separate threads on the server side, one accepting new clients, another sending/receiving data. You will need to use thread synchronization at the access to this collection. However, never use ArrayList. This collection was rendered obsolete as early as of .NET Framework v.2.0, when generic were developed. It was not marked obsolete formally only because it would be find for support of legacy code, but for new development it makes no sense at all; it us more error-prone than generic collections. Use the collections of System.Collections.Generic.

Sorry if this answer is a duplicate on my previous answer, Passing value from javascript to PHP ( Hidden Field )[^].
I'm only adding some detail.

Now, it does not matter where the data is transmitted, from client to server or server to client. Usually, this is an alternative direction, like in a dialog: request-response, and both can carry some information, not only just the confirmation. This is a matter of your application-layer protocol: http://en.wikipedia.org/wiki/Application_layer[^].

Even if you don't call it "protocol", such protocol always exist de-facto, explicit or implied.

—SA
 
Share this answer
 
v2

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900