Java 如何在握手时传递用户名和密码以验证在websocket中的使用?

Java 如何在握手时传递用户名和密码以验证在websocket中的使用?,java,servlets,websocket,tomcat7,Java,Servlets,Websocket,Tomcat7,我正在开发一个群聊应用程序,我想在握手时发送用户名和密码 以下是我的客户端javascript代码: <script type="text/javascript"> var Chat = {}; Chat.socket = null; Chat.connect = (function(host) { if ('WebSocket' in window) { Chat.socket = new WebSocket(ho

我正在开发一个群聊应用程序,我想在握手时发送用户名和密码

以下是我的客户端javascript代码:

<script type="text/javascript">
    var Chat = {};

    Chat.socket = null;

    Chat.connect = (function(host) {
        if ('WebSocket' in window) {
            Chat.socket = new WebSocket(host);
        } else if ('MozWebSocket' in window) {
            Chat.socket = new MozWebSocket(host);
        } else {
            alert("'Error: WebSocket is not supported by this browser.'")
            Console.log('Error: WebSocket is not supported by this browser.');
            return;
        }

        Chat.socket.onopen = function() {
            Console.log('Info: WebSocket connection opened.');
            document.getElementById('chat').onkeydown = function(event) {
                if (event.keyCode == 13) {
                    Chat.sendMessage();
                }
            };
        };

        Chat.socket.onclose = function() {
            document.getElementById('chat').onkeydown = null;
            Console.log('Info: WebSocket closed.');
        };

        Chat.socket.onmessage = function(message) {
            Console.log(message.data);
        };

    });

    Chat.initialize = function() {
        if (window.location.protocol == 'http:') {
            Chat.connect('ws://' + window.location.host
                    + '/WebSocketDemo/ChatWebSocketServlet');
        } else {
            Chat.connect('wss://' + window.location.host
                    + '/WebSocketDemo/ChatWebSocketServlet');
        }
    };

    Chat.sendMessage = (function() {
        var message = document.getElementById('chat').value;
        if (message != '') {
            Chat.socket.send(message);
            document.getElementById('chat').value = '';
        }
    });

    var Console = {};

    Console.log = (function(message) {
        var console = document.getElementById('console');
        var p = document.createElement('p');
        p.style.wordWrap = 'break-word';
        p.innerHTML = message;
        console.appendChild(p);
        while (console.childNodes.length > 25) {
            console.removeChild(console.firstChild);
        }
        console.scrollTop = console.scrollHeight;
    });

    Chat.initialize();
</script>

var Chat={};
Chat.socket=null;
Chat.connect=(函数(主机){
如果('WebSocket'在窗口中){
Chat.socket=新的WebSocket(主机);
}else if(窗口中的“MozWebSocket”){
Chat.socket=新的MozWebSocket(主机);
}否则{
警报(“‘错误:此浏览器不支持WebSocket’”)
Console.log('错误:此浏览器不支持WebSocket');
返回;
}
Chat.socket.onopen=函数(){
log('信息:WebSocket连接已打开');
document.getElementById('chat').onkeydown=函数(事件){
如果(event.keyCode==13){
Chat.sendMessage();
}
};
};
Chat.socket.onclose=函数(){
document.getElementById('chat')。onkeydown=null;
log('Info:WebSocket已关闭');
};
Chat.socket.onmessage=函数(消息){
Console.log(message.data);
};
});
Chat.initialize=函数(){
如果(window.location.protocol=='http:'){
Chat.connect('ws://'+window.location.host
+“/WebSocketDemo/ChatWebSocketServlet”);
}否则{
Chat.connect('wss://'+window.location.host
+“/WebSocketDemo/ChatWebSocketServlet”);
}
};
Chat.sendMessage=(函数(){
var message=document.getElementById('chat')。值;
如果(消息!=''){
聊天。套接字。发送(消息);
document.getElementById('chat')。值='';
}
});
var控制台={};
Console.log=(函数(消息){
var console=document.getElementById('console');
var p=document.createElement('p');
p、 style.wordWrap='break word';
p、 innerHTML=消息;
控制台。附属物(p);
while(console.childNodes.length>25){
console.removeChild(console.firstChild);
}
console.scrollTop=console.scrollHeight;
});
Chat.initialize();
我使用Tomcat7作为服务器

这是我的服务器端代码:

@Deprecated
public class ChatWebSocketServlet extends WebSocketServlet {

    private static final long serialVersionUID = 1L;

    private static final String GUEST_PREFIX = "Guest";

    private final AtomicInteger connectionIds = new AtomicInteger(0);
    private final Set<ChatMessageInbound> connections = new CopyOnWriteArraySet<ChatMessageInbound>();

    @Override
    protected StreamInbound createWebSocketInbound(String subProtocol,
            HttpServletRequest request) {
        return new ChatMessageInbound(connectionIds.incrementAndGet());
    }

    private final class ChatMessageInbound extends MessageInbound {

        private final String nickname;

        private ChatMessageInbound(int id) {
            System.out.println("stage 1");
            this.nickname = GUEST_PREFIX + id;
        }

        @Override
        protected void onOpen(WsOutbound outbound) {
            connections.add(this);
            System.out.println("user:" + this);
            String message = String.format("* %s %s", nickname, "has joined.");
            broadcast(message);
        }

        @Override
        protected void onClose(int status) {
            connections.remove(this);
            String message = String.format("* %s %s", nickname,
                    "has disconnected.");
            broadcast(message);
        }

        @Override
        protected void onBinaryMessage(ByteBuffer message) throws IOException {
            throw new UnsupportedOperationException(
                    "Binary message not supported.");
        }

        @Override
        protected void onTextMessage(CharBuffer message) throws IOException {
            // Never trust the client
            String filteredMessage = String.format("%s: %s", nickname,
                    HTMLFilter.filter(message.toString()));

            broadcast(filteredMessage);
        }

        private void broadcast(String message) {
            for (ChatMessageInbound connection : connections) {
                try {
                    CharBuffer buffer = CharBuffer.wrap(message);
                    connection.getWsOutbound().writeTextMessage(buffer);
                } catch (IOException ignore) {
                    // Ignore
                }
            }
        }
    }
}
@已弃用
公共类ChatWebSocketServlet扩展了WebSocketServlet{
私有静态最终长serialVersionUID=1L;
私有静态最终字符串GUEST\u PREFIX=“GUEST”;
私有最终AtomicInteger ConnectionId=新的AtomicInteger(0);
私有最终集连接=新CopyOnWriteArraySet();
@凌驾
受保护的StreamInbound createWebSocketInbound(字符串子目录,
HttpServletRequest(请求){
返回新的ChatMessageInbound(ConnectionId.incrementAndGet());
}
私有最终类ChatMessageInbound扩展MessageInbound{
私有最终字符串昵称;
私有聊天信息入站(int id){
系统输出打印项次(“第1阶段”);
this.nickname=GUEST\u前缀+id;
}
@凌驾
受保护的void onOpen(WsOutbound-outbound){
连接。添加(此);
System.out.println(“用户:“+this”);
String message=String.format(“*%s%s”,昵称“已加入”);
广播(讯息);
}
@凌驾
受保护的void onClose(int状态){
连接。移除(此);
字符串消息=String.format(“*%s%s”,昵称,
“已断开连接。”);
广播(讯息);
}
@凌驾
受保护的void onBinaryMessage(ByteBuffer消息)引发IOException{
抛出新的UnsupportedOperationException(
“不支持二进制消息。”);
}
@凌驾
受保护的void onTextMessage(CharBuffer消息)引发IOException{
//永远不要相信客户
String filteredMessage=String.format(“%s:%s”,昵称,
HTMLFilter.filter(message.toString());
广播(过滤信息);
}
专用无效广播(字符串消息){
用于(ChatMessageInbound连接:连接){
试一试{
CharBuffer=CharBuffer.wrap(消息);
connection.getWsOutbound().writeTextMessage(缓冲区);
}捕获(IOException忽略){
//忽略
}
}
}
}
}
在这里,我想在实际握手之前发送用户凭证以验证用户身份。
那么,我如何才能做到这一点呢?

有人知道如何在WebSocket中进行身份验证吗?在开始使用WebSocket之前,您应该通过https进行身份验证。但是websocket代码如何验证用户在登录之后的状态对我来说有点弱。您应该阅读并@developerwjk感谢您的回复。