java的websocket_java实现websocket的两种⽅式实例详解⼀、介绍
1.两种⽅式,⼀种使⽤tomcat的websocket实现,⼀种使⽤spring的websocket
3.spring与websocket整合需要spring
4.x,并且使⽤了socketjs,对不⽀持websocket的浏览器可以模拟websocket使⽤
⼆、⽅式⼀:tomcat
使⽤这种⽅式⽆需别的任何配置,只需服务端⼀个处理类,
服务器端代码
package com.Socket;
import java.io.IOException;
import java.util.Map;
import urrent.ConcurrentHashMap;
import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import net.sf.json.JSONObject;
@ServerEndpoint("/websocket/{username}")
public class WebSocket {
private static int onlineCount = 0;
private static Map clients = new ConcurrentHashMap();
private Session session;
private String username;
@OnOpen
public void onOpen(@PathParam("username") String username, Session session) throws IOException {
this.username = username;
this.session = session;
addOnlineCount();
clients.put(username, this);
System.out.println("已连接");
}
@OnClose
public void onClose() throws IOException {
subOnlineCount();
}
@OnMessage
public void onMessage(String message) throws IOException {
JSONObject jsonTo = JSONObject.fromObject(message);
if (!("To").equals("All")){
sendMessageTo("给⼀个⼈", ("To").toString());
}else{
sendMessageAll("给所有⼈");
}
}
@OnError
public void onError(Session session, Throwable error) {
error.printStackTrace();
}
public void sendMessageTo(String message, String To) throws IOException { // BasicRemote().sendText(message);
//AsyncRemote().sendText(message);
for (WebSocket item : clients.values()) {
if (item.username.equals(To) )
AsyncRemote().sendText(message);
}
}
public void sendMessageAll(String message) throws IOException {
for (WebSocket item : clients.values()) {
AsyncRemote().sendText(message);
}
}
public static synchronized int getOnlineCount() {
return onlineCount;
}
public static synchronized void addOnlineCount() {
}
public static synchronized void subOnlineCount() {
}
public static synchronized Map getClients() {
return clients;
}
}
客户端js
var websocket = null;
var username = Item("name");
//判断当前浏览器是否⽀持WebSocket
if ('WebSocket' in window) {
websocket = new WebSocket("ws://" + document.location.host + "/WebChat/websocket/" + username + "/"+ _img); } else {
alert('当前浏览器 Not support websocket')
}
//连接发⽣错误的回调⽅法
setMessageInnerHTML("WebSocket连接发⽣错误");
};
//连接成功建⽴的回调⽅法
setMessageInnerHTML("WebSocket连接成功");
}
//接收到消息的回调⽅法
setMessageInnerHTML(event.data);
}
//连接关闭的回调⽅法
setMessageInnerHTML("WebSocket连接关闭");
}
//监听窗⼝关闭事件,当窗⼝关闭时,主动去关闭websocket连接,防⽌连接还没断开就关闭窗⼝,server端会抛异常。beforeunload = function() {
closeWebSocket();
}
//关闭WebSocket连接
function closeWebSocket() {
websocket.close();
}
发送消息只需要使⽤websocket.send(“发送消息”),就可以触发服务端的onMessage()⽅法,当连接时,触发服务器端onOpen()⽅法,此时也可以调⽤发送消息的⽅法去发送消息。关闭websocket时,触发服务器端onclose()⽅法,此时也可以发送消息,但是不能发送给⾃⼰,因为⾃⼰的已经关闭了连接,但是可以发送给其他⼈。
三、⽅法⼆:spring整合
WebSocketConfig.java
这个类是配置类,所以需要在spring mvc配置⽂件中加⼊对这个类的扫描,第⼀个addHandler是对正常连接的配置,第⼆个是如果浏览器不⽀持websocket,使⽤socketjs模拟websocket的连接。
package com.websocket;
import t.annotation.Bean;
import t.annotation.Configuration;
import org.springframework.fig.annotation.EnableWebSocket;
import org.springframework.fig.annotation.WebSocketConfigurer;
import org.springframework.fig.annotation.WebSocketHandlerRegistry;
import org.springframework.web.socket.handler.TextWebSocketHandler;
@Configuration
@EnableWebSocket
public class WebSocketConfig implements WebSocketConfigurer {
@Override
public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) {
registry.addHandler(chatMessageHandler(),"/webSocketServer").addInterceptors(new ChatHandshakeInterceptor());
registry.addHandler(chatMessageHandler(), "/sockjs/webSocketServer").addInterceptors(new
ChatHandshakeInterceptor()).withSockJS();
}
@Bean
public TextWebSocketHandler chatMessageHandler(){
return new ChatMessageHandler();
}
}
ChatHandshakeInterceptor.java
这个类的作⽤就是在连接成功前和成功后增加⼀些额外的功能,Constants.java类是⼀个⼯具类,两个常量。
package com.websocket;
import java.util.Map;
import org.apache.shiro.SecurityUtils;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.socket.WebSocketHandler;
前端websocket怎么用import org.springframework.web.socket.server.support.HttpSessionHandshakeInterceptor;
public class ChatHandshakeInterceptor extends HttpSessionHandshakeInterceptor {
@Override
public boolean beforeHandshake(ServerHttpRequest request, ServerHttpResponse response, WebSocketHandler wsHandler,
Map attributes) throws Exception {
System.out.println("Before Handshake");
/*
* if (request instanceof ServletServerHttpRequest) {
* ServletServerHttpRequest servletRequest = (ServletServerHttpRequest)
* request; HttpSession session =
* ServletRequest().getSession(false); if (session !=
* null) { //使⽤userName区分WebSocketHandler,以便定向发送消息 String userName =
* (String) Attribute(Constants.SESSION_USERNAME); if
* (userName==null) { userName="default-system"; }
* attributes.put(Constants.WEBSOCKET_USERNAME,userName);
*
* } }
*/
//使⽤userName区分WebSocketHandler,以便定向发送消息(使⽤shiro获取session,或是使⽤上⾯的⽅式)
String userName = (String) Subject().getSession().getAttribute(Constants.SESSION_USERNAME);
if (userName == null) {
userName = "default-system";
}
attributes.put(Constants.WEBSOCKET_USERNAME, userName);
return super.beforeHandshake(request, response, wsHandler, attributes);
}
@Override
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。
发表评论