javaweb与websocket实现功能总结
技术从⼀开始ajax轮询后来改成websocket 碰到的⼀些问题的处理:
websocket的pom依赖
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-websocket</artifactId>
<version>4.0.5.RELEASE</version>
</dependency>
⾸先是配置处理器
import javax.annotation.Resource;
import org.springframework.stereotype.Component;
import org.springframework.fig.annotation.WebMvcConfigurerAdapter;
import org.springframework.fig.annotation.EnableWebSocket;
import org.springframework.fig.annotation.WebSocketConfigurer;
import org.springframework.fig.annotation.WebSocketHandlerRegistry;
/**
* WebScoket配置处理器
* @author Goofy
* @Date 2015年6⽉11⽇下午1:15:09
*/
@Component
@EnableWebSocket
public class WebSocketConfig extends WebMvcConfigurerAdapter implements WebSocketConfigurer {
@Resource
MyWebSocketHandler handler;
public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) {
registry.addHandler(handler, "/ws").addInterceptors(new HandShake());
registry.addHandler(handler, "/ws/sockjs").addInterceptors(new HandShake()).withSockJS();
}
}
2.请求所经过的握⼿主要⽤来将ServerHttpRequest⾥的session的⽤户信息存放在attributes⾥到处理的handle中会⾃动存⼊websocketsession的attribute⾥
import java.util.Map;
import javax.servlet.http.HttpSession;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.http.server.ServletServerHttpRequest;
import org.springframework.web.socket.WebSocketHandler;
import org.springframework.web.socket.server.HandshakeInterceptor;
/**
* Socket建⽴连接(握⼿)和断开
*
* @author Goofy
* @Date 2015年6⽉11⽇下午2:23:09
*/
public class HandShake implements HandshakeInterceptor {
public boolean beforeHandshake(ServerHttpRequest request, ServerHttpResponse response, WebSocketHandler wsHandler, Map<String, Object> attributes) throws Exception {  System.out.println("Websocket:⽤户[ID:" + ((ServletServerHttpRequest) request).getServletRequest().getSession(false).getAttribute("uid") + "]已经建⽴连接");
if (request instanceof ServletServerHttpRequest) {
ServletServerHttpRequest servletRequest = (ServletServerHttpRequest) request;
HttpSession session = ServletRequest().getSession(false);
// 标记⽤户
Long uid = (Long) Attribute("uid");
if(uid!=null){
attributes.put("uid", uid);
}else{
return false;
}
}
return true;
}
public void afterHandshake(ServerHttpRequest request, ServerHttpResponse response, WebSocketHandler wsHandler, Exception exception) {
}
}
Socket处理器处理连接通信或错误关闭等
import java.io.IOException;
SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.CloseStatus;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketHandler;
import org.springframework.web.socket.WebSocketMessage;
import org.springframework.web.socket.WebSocketSession;
import ity.Message;
le.gson.Gson;
le.gson.GsonBuilder;
/**
* Socket处理器
*
* @author Goofy
* @Date 2015年6⽉11⽇下午1:19:50
*/
@Component
public class MyWebSocketHandler implements WebSocketHandler {
public static final Map<Long, WebSocketSession> userSocketSessionMap;
static {
userSocketSessionMap = new HashMap<Long, WebSocketSession>();
}
/**
* 建⽴连接后
*/
public void afterConnectionEstablished(WebSocketSession session)
throws Exception {
Long uid = (Long) Attributes().get("uid");
if ((uid) == null) {
userSocketSessionMap.put(uid, session);
}
}
/**
* 消息处理,在客户端通过Websocket API发送的消息会经过这⾥,然后进⾏相应的处理
*/
public void handleMessage(WebSocketSession session, WebSocketMessage<?> message) throws Exception {
PayloadLength()==0)return;
Message msg=new Gson().Payload().toString(),Message.class);
msg.setDate(new Date());
To(), new TextMessage(new GsonBuilder().setDateFormat("yyyy-MM-dd HH:mm:ss").create().toJson(msg))); }
/**
* 消息传输错误处理
*/
public void handleTransportError(WebSocketSession session,
Throwable exception) throws Exception {
if (session.isOpen()) {
session.close();
}
Iterator<Entry<Long, WebSocketSession>> it = userSocketSessionMap
.entrySet().iterator();
// 移除Socket会话
while (it.hasNext()) {
Entry<Long, WebSocketSession> entry = it.next();
if (Value().getId().Id())) {
System.out.println("Socket会话已经移除:⽤户ID" + Key());
break;
}
}
}
/
**
* 关闭连接后
*/
public void afterConnectionClosed(WebSocketSession session,
CloseStatus closeStatus) throws Exception {
System.out.println("Websocket:" + Id() + "已经关闭");
Iterator<Entry<Long, WebSocketSession>> it = userSocketSessionMap
.entrySet().iterator();
// 移除Socket会话
if (Value().getId().Id())) {
System.out.println("Socket会话已经移除:⽤户ID" + Key());
break;
}
}
}
public boolean supportsPartialMessages() {
return false;
}
/**
* 给所有在线⽤户发送消息
*
* @param message
* @throws IOException
*/
public void broadcast(final TextMessage message) throws IOException {
Iterator<Entry<Long, WebSocketSession>> it = userSocketSessionMap
.entrySet().iterator();
// 多线程发
while (it.hasNext()) {
final Entry<Long, WebSocketSession> entry = it.next();
if (Value().isOpen()) {
// Value().sendMessage(message);
new Thread(new Runnable() {
public void run() {
try {
if (Value().isOpen()) {
}
} catch (IOException e) {
e.printStackTrace();
}
}
}).start();
}
}
}
/**
* 给某个⽤户发送消息
*
* @param userName
* @param message
* @throws IOException
*/
public void sendMessageToUser(Long uid, TextMessage message)
throws IOException {
WebSocketSession session = (uid);
if (session != null && session.isOpen()) {
session.sendMessage(message);
}
}
}
  页⾯
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
String path = ContextPath();
String basePath = ServerName() + ":"
+ ServerPort() + path + "/";
String basePath2 = Scheme() + "://"
+ ServerName() + ":" + ServerPort()
+ path + "/";
%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN"
"/TR/html4/strict.dtd">
<html xmlns="/1999/xhtml" lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title></title>
<script type="text/javascript" src="<%=basePath2%>resources/jquery.js"></script> <style>
textarea {
height: 300px;
width: 100%;
outline: none;
}
input[type=button] {
float: right;
margin: 5px;
width: 50px;
height: 35px;
border: none;
color: white;
font-weight: bold;
outline: none;
}
.clear {
background: red;
}
.send {
background: green;
}
.clear:active {
background: yellow;
}
.send:active {
background: yellow;
}
.msg {
width: 100%;
height: 25px;
outline: none;
}
#content {
border: 1px solid gray;
width: 100%;
height: 400px;
overflow-y: scroll;
}
.from {
background-color: green;
width: 80%;
border-radius: 10px;
height: 30px;
line-height: 30px;
margin: 5px;
float: left;
color: white;
padding: 5px;
font-size: 22px;
}
.to {
background-color: gray;
width: 80%;
border-radius: 10px;
height: 30px;
line-height: 30px;
margin: 5px;
float: right;
color: white;
padding: 5px;
font-size: 22px;
}
.name {
color: gray;
font-size: 12px;
}
.tmsg_text {
color: white;
background-color: rgb(47, 47, 47); font-size: 18px;
border-radius: 5px;
padding: 2px;
}
.fmsg_text {
color: white;
websocket和socketbackground-color: rgb(66, 138, 140); font-size: 18px;
border-radius: 5px;
}
.sfmsg_text {
color: white;
background-color: rgb(148, 16, 16);
font-size: 18px;
border-radius: 5px;
padding: 2px;
}
.tmsg {
clear: both;
float: right;
width: 80%;
text-align: right;
}
.fmsg {
clear: both;
float: left;
width: 80%;
}
</style>
<script>
var path = '<%=basePath%>';
var uid=${uid eq null?-1:uid};
if(uid==-1){
location.href="<%=basePath2%>";
}
var from=uid;
var fromName='${name}';
var to=uid==1?2:1;
var websocket;
if ('WebSocket' in window) {
websocket = new WebSocket("ws://" + path + "/ws?uid="+uid);
} else if ('MozWebSocket' in window) {
websocket = new MozWebSocket("ws://" + path + "/ws"+uid);
} else {
websocket = new SockJS("" + path + "/ws/sockjs"+uid);
}
console.log("WebSocket:已连接");
console.log(event);
};
var data=JSON.parse(event.data);
console.log("WebSocket:收到⼀条消息",data);
var textCss=data.from==-1?"sfmsg_text":"fmsg_text";
$("#content").append("<div class='fmsg'><label class='name'>"+data.fromName+" "+data.date+"</label><div class='"+textCss+"'>"++"</div></div>");
scrollToBottom();
};
console.log("WebSocket:发⽣错误 ");
console.log(event);
};
console.log("WebSocket:已关闭");
console.log(event);
}
function sendMsg(){
var v=$("#msg").val();
if(v==""){
return;
}else{
var data={};
data["from"]=from;
data["fromName"]=fromName;
data["to"]=to;
data["text"]=v;
websocket.send(JSON.stringify(data));
$("#content").append("<div class='tmsg'><label class='name'>我 "+new Date().Format("yyyy-MM-dd hh:mm:ss")+"</label><div class='tmsg_text'>"++"</div></div>");    scrollToBottom();
$("#msg").val("");
}
}
function scrollToBottom(){
var div = ElementById('content');
div.scrollTop = div.scrollHeight;
}
Date.prototype.Format = function (fmt) { //author: meizz
var o = {
"M+": Month() + 1, //⽉份
"d+": Date(), //⽇
"h+": Hours(), //⼩时

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。