简体   繁体   中英

Making a multithreaded chat server with sockets

I'm coding server chat using TCP sockets. I implemented public and private messages. Now, how can I make channels? How can I link channels with socket clients? I made a String[] like this:

if (frase.startsWith("/make")) {
    //crea sala
    String[] privado = frase.split("\\s", 2);
    synchronized (this) {
        end = false;
        for (int i = 0; i < MAX && !end; i++){
            if (salas[i] == null) {
                canal = privado[1];
                salas[i] = canal;
                end = true;
            } else if (privado[1].startsWith(salas[i])) {
                salidaACliente.println("Ya existe " + privado[1] + "\n");
                end = true;
            }
            if (i == MAX - 1) {
                salidaACliente.println("Espacio de canales lleno.\n");
                end = true;
            }
        }
    }
}

For example:

  • 0-channel1
  • 1-channel2

All users can see the created channels using a command /seechannels

String[] salas = new salas[20];

But so far a channel is only a String . How can I now link a channel with a socket using /join channel1 ?

You could, for example, create an array in all of the threads, which stores the channels that the user is part of.

boolean joinedChannels[] = new Boolean[max_channels];

// Remember to intialize the array.

if (cmd == "/joinchannel") {            // cmd here is the issued command
   joinedChannels[args[0]] = true;      // args[] is an array of the arguments
                                        // following the command. This sets the
                                        // desired channel to be active.
} else if (cmd == "/leavechannel") {
   joinedChannels[args[0]] = false;     // And this here sets it inactive.
}

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