基于Tomcate、java、websocket 简单在线聊天
web.xml配置
跟所有servlet 在web.xml进行配置
<servlet>
<servlet-name>socketHome</servlet-name>
<servlet-class>SocketServer</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>socketHome</servlet-name>
<url-pattern>/ws</url-pattern>
</servlet-mapping>
后台代码
SocketServer.java,ws://协议的请求就必须实现WebSocketServlet这个类
import java.util.concurrent.atomic.AtomicInteger;
import javax.servlet.http.HttpServletRequest;
import org.apache.catalina.websocket.StreamInbound;
import org.apache.catalina.websocket.WebSocketServlet;
/**
*
* @author wangbg 通讯入口
*/
@SuppressWarnings("deprecation")
public class SocketServer extends WebSocketServlet {
/**
*
*/
private static final long serialVersionUID = 1L;
/**
* 生成/获取用户
*
* @param reuqest
* @return
*/
private String getUser(HttpServletRequest reuqest) {
Object objectUser = reuqest.getSession().getAttribute("user");
if (objectUser == null) {
objectUser = "游客" + reuqest.getSession().getId();
}
return objectUser.toString();
}
// 实现createWebSocketInbound,在这里初始化自定义的WebSocket连接对象
@Override
protected StreamInbound createWebSocketInbound(String arg0,
HttpServletRequest reuqest) {
// TODO Auto-generated method stub
return new MessageInbound(getUser(reuqest));
}
}
MessageInbound.java,WebSocket连接对象类
代码中的主要实现了onOpen、onTextMessage方法,分别处理用户上线、发送消息,还有onClose方法 不过我没有实现。
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.CharBuffer;
import net.sf.json.JSONObject;
import org.apache.catalina.websocket.WsOutbound;
/**
*
* @author wangbg 通訊交互
*/
@SuppressWarnings("deprecation")
public class MessageInbound extends
org.apache.catalina.websocket.MessageInbound {
private final String user;
public MessageInbound(String user) {
// TODO Auto-generated constructor stub
this.user = user;
}
public String getUser() {
return this.user;
}
/**
* 用户连接触发事件 1 向连接池添加当前用户 2 向在线用户发送当前用户上线消息 3 向当前用户发送在线用户列表
*/
@Override
protected void onOpen(WsOutbound outbound) {
// TODO Auto-generated method stub
super.onOpen(outbound);
// 向连接池添加当前用户
InboundPool.addInbound(this);
JSONObject result = new JSONObject();
// 向在线用户发送当前用户上线消息
InboundPool.sendMessage(this.user + "上线");
// 向当前用户发送在线用户列表
result = new JSONObject();
result.element("onlineUser", InboundPool.getOnlineUser());
InboundPool.sendMessageToUser(this.user, result.toString());
}
@Override
protected void onBinaryMessage(ByteBuffer arg0) throws IOException {
// TODO Auto-generated method stub
}
/**
* 客户端发送消息时触发
*/
@Override
protected void onTextMessage(CharBuffer message) throws IOException {
// TODO Auto-generated method stub
InboundPool.sendMessage(this.user + ":" + message.toString());
}
}
InboundPool.java,连接对象池,管理在线用户的连接
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.CharBuffer;
import net.sf.json.JSONObject;
import org.apache.catalina.websocket.WsOutbound;
/**
*
* @author wangbg 通訊交互
*/
@SuppressWarnings("deprecation")
public class MessageInbound extends
org.apache.catalina.websocket.MessageInbound {
private final String user;
public MessageInbound(String user) {
// TODO Auto-generated constructor stub
this.user = user;
}
public String getUser() {
return this.user;
}
/**
* 用户连接触发事件 1 向连接池添加当前用户 2 向在线用户发送当前用户上线消息 3 向当前用户发送在线用户列表
*/
@Override
protected void onOpen(WsOutbound outbound) {
// TODO Auto-generated method stub
super.onOpen(outbound);
// 向连接池添加当前用户
InboundPool.addInbound(this);
JSONObject result = new JSONObject();
// 向在线用户发送当前用户上线消息
InboundPool.sendMessage(this.user + "上线");
// 向当前用户发送在线用户列表
result = new JSONObject();
result.element("onlineUser", InboundPool.getOnlineUser());
InboundPool.sendMessageToUser(this.user, result.toString());
}
@Override
protected void onBinaryMessage(ByteBuffer arg0) throws IOException {
// TODO Auto-generated method stub
}
/**
* 客户端发送消息时触发
*/
@Override
protected void onTextMessage(CharBuffer message) throws IOException {
// TODO Auto-generated method stub
InboundPool.sendMessage(this.user + ":" + message.toString());
}
}
index.jsp 页面访问及交互
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
<body>
<input type="text" id="message" size="60" />
<input type="button" id="send" value="发送" />
<br>
<div id="panel"></div>
</body>
<script type="text/javascript">
var panel = document.getElementById('panel');
var message = document.getElementById('message');
var send = document.getElementById('send')
// 控制台输出对象
var console = {
log : function(text) {
panel.innerHTML += text + "<br>";
}
};
// WebSocket
var socketBox = {
socket : null, // WebSocket连接对象
host : '', // WebSocket连接 url
connect : function() { // 连接服务器
window.WebSocket = window.WebSocket || window.MozWebSocket;
if (!window.WebSocket) { // 检测浏览器支持
console.log('Error: 请升级到ie10+浏览器 .');
return;
}
// 创建连接并注册响应函数
this.socket = new WebSocket(this.host);
this.socket.onopen = function() {
console.log("连接服务器.");
};
this.socket.onmessage = function(res) {
if (res.type == "message") {
console.log(res.data);
}
};
this.socket.onclose = function() {
console.log("服务器断开 .");
socketBox.socket.onclose();
socketBox.socket = null; // 清理
};
},
send : function(message) { // 发送消息方法
if (this.socket) {
this.socket.send(message);
return true;
}
console.log('请先连接服务器 !!!');
return false;
}
};
// 初始化WebSocket连接 url
socketBox.host = (window.location.protocol == 'http:') ? 'ws://' : 'wss://';
socketBox.host += window.location.host + '/websocket/ws';
// 初始化按钮点击事件函数
send.onclick = function() {
var ms = message.value;
if (!ms)
return;
if (!socketBox.send(ms))
return;
message.value = '';
};
if (!socketBox.socket)
socketBox.connect();
</script>
</body>
</html>