在原WebSocket聊天室的基础上,增加了显示当前信息是谁发出的、实现了退出当前会话功能和对界面进行了简单的优化。
待解决部分:登陆时由客户端向服务器传userName的时候中文会出现乱码。
客户端池代码:
package cn.com.demo.websocket.servlet;
import java.io.IOException;
import java.nio.CharBuffer;
import java.util.HashSet;
import java.util.Map;
import java.util.Hashtable;
import java.util.Set;
public class ClientPools {
private static Set<MyMessageInbound> clients = new HashSet<MyMessageInbound>();
private static Map<String,MyMessageInbound> clientsMap = new Hashtable<String,MyMessageInbound>();
public static void addClient(MyMessageInbound client)
{
clients.add(client);
}
public static void addClient(String userName,MyMessageInbound client)
{
clientsMap.put(userName,client);
}
public static Set<String> getAllUserName()
{
return clientsMap.keySet();
}
public static void removeClient(MyMessageInbound client)
{
clientsMap.remove(client.getName());
System.out.println(client.getName()+"成功退出!");
}
public static void sendLoginMessage(String message)
{
}
public static void sendMessage(String message)
{
for(String key:clientsMap.keySet())
{
try {
//给client发送消息
clientsMap.get(key).getWsOutbound().writeTextMessage(CharBuffer.wrap(message));
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
MyMessageInbound代码,其中对onClose()进行了重写,增加了向客户端发送退出后的当前用户列表和显示XX退出了
package cn.com.demo.websocket.servlet;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.CharBuffer;
import java.util.Set;
import org.apache.catalina.websocket.MessageInbound;
import org.apache.catalina.websocket.WsOutbound;
public class MyMessageInbound extends MessageInbound {
private String name;
public MyMessageInbound(String name){
this.name = name;
}
public String getName()
{
return this.name;
}
@Override
protected void onClose(int status) {
ClientPools.removeClient(this);
ClientPools.sendMessage(this.name+"离开了!");
Set<String> userNames = ClientPools.getAllUserName();
String str ="{type:'userList',value:[";
if(userNames!=null)
{
for(String name:userNames)
{
str = str+"'"+name+"',";
}
}
str = str + "]}";
ClientPools.sendMessage(str);
System.out.println("用户退出");
}
@Override
protected void onOpen(WsOutbound outbound) {
ClientPools.addClient(this);
ClientPools.sendMessage(this.name+"上线了!");
Set<String> userNames = ClientPools.getAllUserName();
String str ="{type:'userList',value:[";
if(userNames!=null)
{
for(String name:userNames)
{
str = str+"'"+name+"',";
}
}
str = str + "]}";
ClientPools.sendMessage(str);
}
@Override
protected void onBinaryMessage(ByteBuffer arg0) throws IOException {
// TODO Auto-generated method stub
}
@Override
protected void onTextMessage(CharBuffer arg0) throws IOException {
//有消息过来就会触发这个事件,把当前消息,推送给其他client
ClientPools.sendMessage(name+":"+arg0.toString());
}
}
MyMessageServlet代码,由于要匹配当前用户名,所以在原来的基础上从客户端获取了userName:
package cn.com.demo.websocket.servlet;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.catalina.websocket.StreamInbound;
import org.apache.catalina.websocket.WebSocketServlet;
@WebServlet(urlPatterns = {"/testMsg"})
public class MyMessageServlet extends WebSocketServlet {
@Override
protected StreamInbound createWebSocketInbound(String arg0,
HttpServletRequest arg1) {
String userName = arg1.getParameter("userName");
MyMessageInbound inbound = new MyMessageInbound(userName);
System.out.println(inbound.hashCode());
ClientPools.addClient(userName,inbound);
return inbound;
}
}
客户端代码,其中退出后清空标签内容由于没有使用jQuery,所以直接用document.getElementById("Layer1").innerHTML="";进行清空,有内存泄漏的风险。
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title></title>
<style type="text/css">
<!--
#Layer1 {
position: absolute;
left: 215px;
top: 27px;
width: 677px;
height: 400px;
z-index: 1;
display: none;
}
#Layer2 {
position: absolute;
left: 215px;
top: 441px;
width: 678px;
height: 72px;
z-index: 2;
display: none;
}
#Layer3 {
position: absolute;
left: 908px;
top: 38px;
width: 137px;
height: 474px;
z-index: 3;
}
-->
</style>
<script type="text/javascript">
var webSocket;
function toSend() {
var _msg = document.getElementById("msg").value;
webSocket.send(_msg);
}
function toSendUser() {
document.getElementById("Layer1").style.display="block";
document.getElementById("Layer2").style.display="block";
document.getElementById("Layer4").style.display="none";
var _value = document.getElementById("name").value;
webSocket = new WebSocket(
"ws://localhost:8080/WebSocketTalk/testMsg?userName=" + _value);
webSocket.onopen = function() {
}
webSocket.onclose = function() {
}
webSocket.onmessage = function(msgObj) {
var _usersStr = msgObj.data;
try{
var _jsonObj = eval("("+_usersStr +")");
if (_jsonObj) {
if (_jsonObj.type == "userList") {
var _userList = "";
for ( var i = 0; i < _jsonObj.value.length; i++) {
_userList = _userList + _jsonObj.value[i] + "<br>";
}
document.getElementById("Layer3").innerHTML = _userList;
}
}
}catch(e)
{
document.getElementById("Layer1").innerHTML = document
.getElementById("Layer1").innerHTML
+ "<br/>" + msgObj.data;
}
}
}
function closeWs(){
document.getElementById("Layer1").style.display="none";
document.getElementById("Layer2").style.display="none";
document.getElementById("Layer3").style.display="none";
document.getElementById("Layer4").style.display="block";
document.getElementById("Layer1").innerHTML="";
document.getElementById("Layer3").innerHTML="";
webSocket.close();
}
</script>
</head>
<div id="Layer4">
<input type="text" name="userName" id="name" />
<br> <input type="submit" value="登陆" onclick="toSendUser()"/>
</div>
<body>
<div id="Layer1"></div>
<div id="Layer2">
<label> <textarea name="mes" cols="50" rows="2" id="msg"></textarea>
<input type="submit" name="Submit" value="发送" onclick="toSend()"/>
<input type="submit" name="Close" value="离开" onclick="closeWs()">
</label>
</div>
<div id="Layer3"></div>
</body>
</html>