直接上代码
chat.html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>点对点聊天</title>
<link type="text/css" rel="stylesheet" href="style.css" />
</head>
<body>
<div id="to">发送给:[<span class="users">所有人</span>]</div>
<div id='container'>
<div id="left_panel">
<div id="left_top">
<!-- <div class="mes from_me">FROM ME</div>
<div class="mes to_me">TO ME</div> -->
</div>
<div id="left_bottom" contentEditable="true"></div>
</div>
<div id="right_panel">
<div id="right_top">
</div>
<div id="right_bottom">
<input type="text" id="user_name" placeholder="User Name" maxlength="10" required/>
<input type="button" id="login" value="登录" onclick="login()"/>
</div>
</div>
</div>
<script>
var userName;
var toUser="";
var websocket=null;
function choose(arg){
toUser=arg.innerHTML;
document.getElementById("to").innerHTML='发送给:[<span class="users">'+toUser+'</span>]';
if(toUser==='所有人')toUser='';
}
function login(){
if(!document.getElementById("user_name").checkValidity())return ;
userName = document.getElementById("user_name").value;
if(userName=="")return;
ws();
}
function ws(){
if('WebSocket' in window){
websocket = new WebSocket("ws://"+location.host+"/Test/chat?id="+userName);
//连接成功建立的回调方法
websocket.onopen = function(event){
console.log("websocket open");
var opt = document.getElementById("right_bottom");
opt.innerHTML='<input type="button" id="login" value="发送" onclick="send()" style="margin-top:50px" />';
}
//连接发生错误的回调方法
websocket.onerror = function(){
console.log("websocket error");
alert("登录失败");
};
//连接关闭的回调方法
websocket.onclose = function(){
console.log("websocket close");
var opt = document.getElementById("right_bottom");
opt.innerHTML='<input type="text" id="user_name" placeholder="User Name" maxlength="10" required/><input type="button" id="login" onclick]="login()" value="登录"/>';
};
//接收到消息的回调方法
websocket.onmessage = function(e){
var json = JSON.parse(e.data);
if((typeof json.to) == 'undefined'){
var html = '<div class="users" onclick="choose(this)">所有人</div>';
for(var k in json){
html+='<div class="users" onclick="choose(this)">'+json[k]+'</div>';
}
document.getElementById("right_top").innerHTML=html;
}else{
var record = document.getElementById("left_top");
var html = '<div class="mes to_me">'+json.from+' : '+json.content+'</div>';
record.innerHTML+=html;
}
};
}else alert("Not Support!");
}
window.onbeforeunload = function(){
if(null!=websocket)
websocket.close();
};
function send(){
var input = document.getElementById("left_bottom");
var mes={
from:userName,
to:toUser,
content:input.innerHTML
};
if(null!=websocket)websocket.send(JSON.stringify(mes));
var html = '<div class="mes from_me">'+input.innerHTML+' : '+userName+'</div>';
document.getElementById("left_top").innerHTML+=html;
input.innerHTML='';
}
</script>
</body>
</html>
ChatServlet
package com.test;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import javax.websocket.OnClose;
import javax.websocket.OnError;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.ServerEndpoint;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
@ServerEndpoint("/chat")
public class ChatServlet {
private String id;
private static ConcurrentMap<String,ChatServlet>users = new ConcurrentHashMap<>();
private Session session;
private void sendMessage(String mes){
this.session.getAsyncRemote().sendText(mes);
}
@OnOpen
public void onOpen(Session session){
this.session = session;
Map<String,List<String>>map = session.getRequestParameterMap();
id = map.get("id").get(0);
users.put(id, this);
List<String>list =new ArrayList<>( users.keySet());
Set<String>key = users.keySet();
for(String k: key){
users.get(k).sendMessage(JSONArray.fromObject(list).toString());
}
}
@OnClose
public void onClose(){
users.remove(id);
}
/**
* 收到客户端消息后调用的方法
* @param message 客户端发送过来的消息
* @param session 可选的参数
*/
@OnMessage
public void onMessage(String message, Session session) {
System.out.println("来自客户端的消息:" + message);
//here is word filter
JSONObject json = JSONObject.fromObject(message);
Mes mes = (Mes)JSONObject.toBean(json,Mes.class);
if(mes.getTo().isEmpty()){
Set<String>key = users.keySet();
for(String k: key){
if(k.equals(mes.from))continue;
users.get(k).sendMessage(message);
}
}else{
ChatServlet toServlet = users.get(mes.getTo());
if(null!=toServlet){
toServlet.sendMessage(message);
}
}
}
@OnError
public void onError(Session session, Throwable error){
error.printStackTrace();
}
}
OK
测试浏览器: Chrome
服务器环境: java8+tomcat8