简体   繁体   English

有没有办法只在 Java 套接字中从服务器向一个客户端发送消息?

[英]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.请注意,我想保持类方法通用,以便我可以在 GUI (Javafx) 控制器类上使用它们。 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.只需添加一种 cookie。 A cookie is nothing more than a string that's sent along with a request. cookie 只不过是随请求一起发送的字符串。

 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.只有当人们成功登录时,才会将 cookie id 提供给他们,并且他们在发送到服务器以验证他们的每个后续请求时将其发送回。

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"如果您查看普通的 http 标头,您会看到许多元数据,这些元数据对于服务器了解如何处理数据、请求者期望/接受哪些数据、使用何种语言、cookie 是什么等非常有用。您可以考虑在您的套接字处理程序中编写这样一个简单的东西,以便能够翻译客户端“想要”的内容

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.理想情况下,您应该使用支持安全连接的安全网络传输库,如果您坚持要编写自己的实现,至少使用SSLServerSocket

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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