java websocket服务器:我可以识别客户端吗?

时间:2014-05-15 15:29:20

标签: java websocket

我想知道是否可以区分连接到websocket服务器的客户端。在我的项目中,我必须能够从多个客户端发送消息并将其发送到特定客户端。所以我的问题是:有没有办法能够识别不同的客户? 我尝试在Session Interface中使用getId()方法,但它对我来说没用?

1 个答案:

答案 0 :(得分:0)

当您注册新的web_socket客户端时,您可以发送客户端信息,例如user_mail或仅仅是一个guid,例如:

HTML PAGE

var pagesessionid = generateGuid();
ws.connect('ws://' + window.location.host + window.location.pathname + 'ws?myclientparam=' + pagesessionid);
or

ws.connect('ws://' + window.location.host + window.location.pathname + 'ws?myclientparam=' + userid);

Servlet代码

    public class BrowserWebSocket extends WebSocketServlet {
...
...
..
    @Override
    protected StreamInbound createWebSocketInbound(String string, HttpServletRequest hsr) {

        String myclientvalue= "";


        if (hsr.getParameter("myclientparam") != null) {
            myclientvalue= hsr.getParameter("myclientparam");

ClientWebSocket webSocket = new ClientWebSocket(myclientvalue);

Web套接字客户端类:

public class ClientWebSocket extends MessageInbound implements Serializable {
    public WsOutbound outbound;
    public String _myclient= "";
    public ClientWebSocket(String myclient) {
        _myclient= myclient;
    }

您可以使用myclient给客户。

这里我使用了带有tomcat websocket的标准servlet,但对于其他情况也是如此

我希望它有所帮助