简体   繁体   中英

is there a way to send a message from server to one client only in Java sockets?

I'm trying to build a server and client app. The client will send login data (email and password) to the server. then the server will respond to the client whether the login data is correct or not. the problem is I want the server to respond only to the client that has sent the login data only. Note that I want to keep the class methods generic so that I can use them on GUI (Javafx) controller classes. how can I achieve this?

public class ServerConnector extends Thread{

    public static final int PORT_NO = 5005;
    private ServerSocket serverSocket;

    /**
     * Starts the server
     */
    public void startServer() {
       this.start();
    }

    @Override
    public void run() {
       Socket clientSocket;
        try {
            serverSocket = new ServerSocket(PORT_NO);
            while (true) {
                clientSocket = serverSocket.accept();
                new ClientHandler(clientSocket);
            }

        } catch (IOException ex) {
            ex.printStackTrace();
        } 
    }
}
public class ClientHandler extends Thread {

    private DataInputStream dis;
    private PrintStream ps;
    private Socket clientSocket;


    public static Vector<ClientHandler> clientThreads = new Vector<ClientHandler>();

    public ClientHandler(Socket s) {
        try {         
            this.clientSocket = s;
            dis = new DataInputStream(clientSocket.getInputStream());
            ps = new PrintStream(clientSocket.getOutputStream());
            clientThreads.add(this);
            start();
        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }

    public void printMsg(String msg) {
        System.out.println(msg);
    }

    @Override
    public void run() {
        while (true) {

            try {
                String str = dis.readLine();
                if(str.equals("JavaTODO_ClientFINISH"))
                {
                    System.out.println("JavaTODO_ClientFINISH");
                    clientThreads.remove(this);
                    this.stop();
                }
                else
                {
                    System.out.println(str);
                }
            } catch (IOException ex) {
               ex.printStackTrace();
            } 
        }
    }

    /**
     * sends message to all clients connected to the server
     *
     * @param msg to be sent
     */
    public static void sendToAll(String msg) {
        for (ClientHandler ch : clientThreads) {
            ch.ps.println(msg);
        }
    }

    /**
     * sends message to one client
     *
     * @param msg to be sent to one client
     */
    public void sendToOneClient(String msg,int index) {     
            ps.println(msg);
            //clientThreads.get(index).ps.println(msg);
            //psStatic.println(msg);    
    }

    /**
     * close the open connection and release resources
     */
    public void closeConnection() {
        try {
            dis.close();
            ps.close();
            clientSocket.close();
        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }
}

Just add a type of cookie. A cookie is nothing more than a string that's sent along with a request.

 cookie=login_id:33384adeg73eg344;

Only when people have successfully logged in, the cookie id is given to them, and they send it back along on every subsequent request that's sent to the server to authenticate them.

A small illustration of how it would work.

流程图

If you take a look at normal http headers you see a lot of meta data that's useful to servers to know how to handle the data, what data the requester expects/accepts, in what language, what the cookies are, etc.. You could consider writing a simple thing like this in your socket handler, to be able to translate what the client "wants"

accept: application/json, text/javascript, */*; q=0.01
accept-encoding: gzip, deflate, br
accept-language: en-US,en;q=0.9
cache-control: no-cache
content-length: 489
content-type: application/x-www-form-urlencoded; charset=UTF-8
cookie: id=foobar
origin: https://stackoverflow.com

But I suggest you look into security as well. These transmissions are all easily intercepted by network sniffers and the like, and can be spoofed. Ideally you'd use a secure network transport library that supports secure connections, at least SSLServerSocket if you insist on writing your own implementation.

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