一、前言
由于近来公司项目比较闲,所以一时兴起想研究下jdk1.7的新功能——WebSocket,初试WebSocket,所以不完善处欢迎各位大牛前来指正
二、环境搭建
1.安装1.7以上的jdk版本,同时Tomcat的版本也要是7.0以上的版本(请自行去官网下载)
2.创建工程,
三、代码编写
注: 这里暂时只写一个公共聊天的Demo后续将加入队伍聊天 私聊 国家聊天等功能
1.后台Java代码
package chatServer;
/******************************************
* WebSocket后台数据处理
* @author LiHuan
* @date 2016-11-19 11:48:47
******************************************/
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CopyOnWriteArraySet;
import javax.websocket.EndpointConfig;
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;
@ServerEndpoint(value="/chat",configurator=HttpSessionConfigurator.class)
public class WebSocket {
// 静态变量用来记录当前在线连接数
private static int onlineCount = 0;
//webSocket 会话
private Session session;
//注意此处必须使用静态私有属性
private static CopyOnWriteArraySet<WebSocket> webSocketSet = new CopyOnWriteArraySet<WebSocket>();
//在线用户列表
@SuppressWarnings("unused")
private static List<String> userList = new ArrayList<String>();
/********************************
* 连接成功调用的方法
* @param session
*******************************/
@OnOpen
public void onOpen(Session session, EndpointConfig config)
{
this.session = session;
webSocketSet.add(this);
addOlineCount();
String message="新用户加入了,总数为"+getOnlineCount();
broadcast(message);
}
/********************************
* 关闭连接
*******************************/
@OnClose
public void onClose()
{
webSocketSet.remove(this);
subOnlineCount();
String message= "用户离开了,总数为"+getOnlineCount();
broadcast(message);
}
/********************************
* 收到客户端信息后调用的方法
* @param msg
* @param session
*******************************/
@OnMessage
public void onMessage(String msg)
{
//处理接受到的信息
msg.split("|");
int i = msg.indexOf("|");
String username = msg.substring(0,i);
msg = username+":"+msg.substring(i+1);
//广播消息
broadcast(msg);
}
/********************************
* 发生错误时调用
* @param session
* @param error
*******************************/
@OnError
public void onError(Session session, Throwable error)
{
error.printStackTrace();
}
/********************************
* 广播消息
* @param message
*******************************/
public void broadcast(String message)
{
for(WebSocket chat: webSocketSet){
try {
chat.session.getBasicRemote().sendText(message);
} catch (IOException e) {
e.printStackTrace();
continue;
}
}
}
/********************************
* 对特定用户发送消息
* @param message
* @param session
*******************************/
public void singleSend(String message, Session session)
{
try {
session.getBasicRemote().sendText(message);
} catch (IOException e) {
e.printStackTrace();
}
}
public static synchronized void subOnlineCount() {
WebSocket.onlineCount--;
}
public static synchronized int getOnlineCount() {
return onlineCount;
}
public static synchronized void addOlineCount() {
WebSocket.onlineCount++;
}
}
package chatServer;
import javax.servlet.http.HttpSession;
import javax.websocket.HandshakeResponse;
import javax.websocket.server.HandshakeRequest;
import javax.websocket.server.ServerEndpointConfig;
public class HttpSessionConfigurator extends ServerEndpointConfig.Configurator {
@Override
public void modifyHandshake(ServerEndpointConfig config, HandshakeRequest request, HandshakeResponse response){
HttpSession httpSession = (HttpSession)request.getHttpSession();
config.getUserProperties().put(HttpSession.class.getName(),httpSession);
}
}
2.JSP
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<base href="<%=basePath%>">
<title>WebChat Demo</title>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
<script type="text/javascript" src="<%=basePath %>js/jquery-1.11.1.min.js"></script>
<script type="text/javascript" src="<%=basePath %>js/chat.js"></script>
</head>
<body>
<div style="border: 1px solid red;width: 450px;height: 200px;">
<div style="width: 180px;height: 200px;float: left">
<table width="100%"height="70%">
<tr><td align="center" colspan="2">WebChat</td></tr>
<tr><td colspan="2"><hr width="100%" color="black"/></td></tr>
<tr><td align="right">UserName:</td><td align="left"><input id="username" type="text" /></td></tr>
<tr><td align="right">Message:</td><td align="left"><input id="msg" type="text" /></td></tr>
<tr><td colspan="2" align="center"><input οnclick="msg.send()" value="Send" type="button" /></td></tr>
</table>
</div>
<div id="chart-message" style="border-left:1px solid black;width: 200px;height: 200px;float: right;overflow: auto;"></div>
</div>
</body>
</html>
3.JS
var sokect = null;
$(function()
{
if ('WebSocket' in window)
{
//此处路径'/chat'是由工程名+java注解路径组成
//由于我的项目根的上下文是'/'所以省略了
sokect = new WebSocket('ws://'+window.location.host+'/chat');
}
else
{
alert('您的浏览器不支持聊天功能,请更换或升级浏览器!');
return;
}
/************
* 打开连接
*************/
sokect.onopen = function ()
{
log('温馨提示: WebSocket connection opened.','red');
};
/**************
* 接受信息
*************/
sokect.onmessage = function (event)
{
log(event.data);
};
/**************
* 连接关闭
*************/
sokect.onclose = function (event)
{
log('Info: WebSocket connection closed, Code: ' + event.code + (event.reason == "" ? "" : ", Reason: " + event.reason),'red');
};
$('#msg').keydown(function(e){
if(e.keyCode==13){
msg.send();
}
});
});
var msg=
{
/**************
* 发送消息
**************/
send:function()
{
var username = $('#username').val();
if(username==""||username==null)
{
alert('请输入用户名');
return false;
}
var msg = $('#msg').val();
if(msg==""||msg==null)
{
alert('不可发送空消息');
return false;
}
if (sokect != null)
{
//log(username+' Send: ' + msg);
sokect.send(username+'|'+msg);
$('#msg').val('');
}
else
{
log('连接到频道失败,请检查网络!');
}
}
}
function log(message){
$('#chart-message').append('<p style="font-size: 12px;">'+message+'</p>');
var console = document.getElementById('chart-message');
while (console.childNodes.length > 80) {
console.removeChild(console.firstChild);
}
console.scrollTop = console.scrollHeight;
}
document.addEventListener("DOMContentLoaded", function() {
// Remove elements with "noscript" class - <noscript> is not allowed in XHTML
var noscripts = document.getElementsByClassName("noscript");
for (var i = 0; i < noscripts.length; i++) {
noscripts[i].parentNode.removeChild(noscripts[i]);
}
}, false);
四、运行效果
五、注意事项
tomcat 项目部署好后需要删除 websocket-api.jar
六、项目下载(包含了jar包)
下篇我们将实现国家聊天功能