Passing an id to server socket

Asked

Viewed 131 times

1

Each client contains a fixed id would have as I amnesze that id to the server to then be able to send messages to clients with specific ids?

Server:

    import java.io.IOException;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;

public class Server {

    List<PrintWriter> writers = new ArrayList<>();
    List<Thread> clients = new ArrayList<>();
    Thread t;

    public Server() {
        ServerSocket server;
        try {
            server = new ServerSocket(6000);
            while (true) {
                Socket socket = server.accept();
                t = new Thread(new listenClient(socket));
                t.setName(socket.getInetAddress().toString());
                clients.add(t);
                t.start();
                PrintWriter p = new PrintWriter(socket.getOutputStream());
                writers.add(p);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    private void sendAll(String text) {
        for (PrintWriter w : writers) {
            w.println(text);
            w.flush();
        }
    }

    private class listenClient implements Runnable {
        Scanner scan;

        public listenClient(Socket socket) {
            try {
            scan = new Scanner(socket.getInputStream());
            } catch (IOException e) {

                e.printStackTrace();
            }
        }

        @Override
        public void run() {
            String text;

            while ((text = scan.nextLine()) != null) {
                sendAll(text);
                System.out.println(text);
            }

        }

    }

    public static void main(String[] args) {
        new Server();

    }

This very simple and as you can see I tried to do something by ip but I realized that it would give conflict more forward and would have to be by id even passed by the client

1 answer

2


I’m not sure what the future use of the program is but if each client could enter with a name and you validated that name to never be repeated you had a good "ID" to manage messages.

A few lines of code to set an example to see if you can understand:

    //************ Metodos connetar | isconnect |
        public void Connect() {

            if (!Login.isEmpty()) {
                //message é uma classe onde envio toda a informação que quero enviar
                this.message = new Chatmessage();
                this.message.setAction(Action.CONNECT); //no servidor tenho um "Case" que //consoante a "action" diferente, faz diferentes usos
// exemplos de "action": CONNECT, DISCONNECT, SENDONE,SENDALL;
                this.message.setName(Login);
                this.message.setcodigo(codigo);
                this.socket =connect();

                new Thread(new ListenerSocket(this.socket)).start();

                send(message);
            }

        }

Then on the server I have:

while ((message = (Chatmessage) input.readObject()) != null || stop == false) {
                    Action action = message.getAction();
                    if (action.equals(Action.CONNECT)) {
                        boolean isConnect = connect(message, output);// verifica se o //cliente novo que chegou ao server se pode connetar, se a resposta for "sim" continua no //programa  se a resposta for "nao" o server nao deixa entrar:
                        if (isConnect) {
                            System.out.println(""+ message.getName());
                            if (message.getAdmin()) {
//********************** Guarda os ADMINS                                
                                Admins.put(message.getcodigo(), output);
//********************** Guarda em cada codigo que user é que está logado                            
                                mapUsercodigo.put(message.getcodigo(), message.getName());
//********************** Guarda para cada codigo o socket, que é usado para cada computador
                                mapcodigosOnlines.put(message.getcodigo(), output);
                            } else {
//********************** Guarda os USERS
                                Users.put(message.getcodigo(), output);                            
                                mapcodigo.put(message.getcodigo(), codigo);
                                sendonlines();

                            }    

                        } else {
                            return;
                        }
                    } else if (action.equals(Action.DISCONNECT)) {
                        disconnect(message, output);
                        sendonlines();
                        return;
                    }

This implementation already has many changes but it was practically all created from this excellent tutorial

Link

Browser other questions tagged

You are not signed in. Login or sign up in order to post.