简体   繁体   中英

Java TCP Client-Server Connection: always open to listen from server

I am creating a Chat with Java using Swing. I am almost done with the basics, I just can not Broadcast the message to every client, somehow, the client is not getting the message. I have:

static Vector<ClientHandler> ar = new Vector<>();
static void Broadcast() throws IOException
{
    for (int i = 0; i < ar.size(); i++)
    {
        try
        {
            DataOutputStream out = new DataOutputStream(ar.get(i).client.getOutputStream());

            out.writeUTF(String.valueOf(ar.size()));
        }
        catch (Exception ex)
        {
            ex.printStackTrace();
        }
    }
}

which works fine, I have all the clients connected and stuff.

I have made the client-sided part multi-threaded, so each user can have a unique window and details, I have this part where I send the text to the server-sided part:

        public void actionPerformed(ActionEvent e) 
        {
            try
            {
                out.writeUTF(String.valueOf(clientSocket.getLocalPort()));
                String resp = in.readUTF();

                System.out.println(resp); // this only outputs for one client, is it not supposed to output it for every client on the thread, since this piece of code is shared with every other thread, and every other thread is waiting?
            }
            catch (Exception ex)
            {
                ex.printStackTrace();
            }

        }

Thank you in advance!

EDIT:

For those who wonder, I fixed this part by fixing the logic. There seems to have been no need for a multi-threaded client-sided frame too. I just removed the multi-threaded part and it is seems to be working fine.

What is the point of the exact question? Does that mean you can not figure out whether it's a server issue or a client issue?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM