Suresh Kinta
Suresh Kinta

Reputation: 33

networkstream only sends data to the last IP connected to the server

i have a program that multiple clients would be able to connect to a server using a socket.

        private void performConnect()
    {

        while (true)
        {
            if (myList.Pending())
            {
                thrd = thrd + 1;
                tcpClient = myList.AcceptTcpClient();

                IPEndPoint ipEndPoint = (IPEndPoint)tcpClient.Client.RemoteEndPoint;
                string clientIP = ipEndPoint.Address.ToString();
                nStream[thrd] = tcpClient.GetStream();
                currentMsg = "\n New IP client found :" + clientIP;
                recieve[thrd].Start();

                this.Invoke(new rcvData(addNotification));
                try
                {
                    addToIPList(clientIP);

                }
                catch (InvalidOperationException exp)
                {
                    Console.Error.WriteLine(exp.Message);
                }
                Thread.Sleep(1000);
            }

            }



    }

then the server could send data (chat messages) to a chosen client, using this code.

        private void sendData(String data)
    {
        IPAddress ipep =IPAddress.Parse(comboBox1.SelectedItem.ToString());
        Socket server = new Socket(AddressFamily.InterNetwork , SocketType.Stream, ProtocolType.Tcp);
        IPEndPoint ipept = new IPEndPoint( ipep, hostPort);
        NetworkStream nStream = tcpClient.GetStream();
        ASCIIEncoding asciidata = new ASCIIEncoding();
        byte[] buffer = asciidata.GetBytes(data);
        if (nStream.CanWrite)
        {
            nStream.Write(buffer, 0, buffer.Length);
            nStream.Flush();
        }
    }

the problem is that whatever IP i choose from the combo box, the message i send would always be directed/sent to the last IP that connected to the server.. Please somebody help me find the error.. all help would be appreciated, thanks in advance!

Upvotes: 0

Views: 279

Answers (1)

nullptr
nullptr

Reputation: 11058

That's because in sendData you perform

NetworkStream nStream = tcpClient.GetStream();

where tcpClient variable stores the last accepted connection. Instead of this, you should use your nStream[] array which stores all the connected streams.

Upvotes: 1

Related Questions