Java实现WebSocket
Java实现WebSocket
1.WebSocket
平时开发的时候,对于⼀些平常的需求是不会使⽤基于WebSocket开发的需求。但是在⼀些特定场景,⽐如:主动推送,模拟聊天等等,因为WebSocket建⽴等实际上是⼀个长链接。
2.基于Java实现WebSocket的开发
代码⽅⾯很简单。
@Configuration
public class WebSocketConfig {
@Bean
public ServerEndpointExporter serverEndpointExporter(){
return new ServerEndpointExporter();
}
}
2.Server 的实现
基于注解的实现,
核⼼注解:
ServerEndpoint:标⽰⼀个websocket,两个参数设置:
value指定请求地址。
configurator:配置请求拦截类。
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import javax.websocket.*;
import java.io.IOException;
import urrent.ConcurrentHashMap;
import urrent.ConcurrentMap;
import urrent.CopyOnWriteArrayList;
/**
* socket推送消息(服务端)
*/
@ServerEndpoint(value ="/socket/websocket/{idno}", configurator = SocketServerConfigurator.class)
/
/@ServerEndpoint(value = "/socket/websocket/{idno}")
@Component
public class WebSocketServer {
private final Logger logger = Logger(WebSocketServer.class);
private static int onlineCount =0;
private static CopyOnWriteArrayList<WebSocketServer> webSockets =new CopyOnWriteArrayList<>();
private static ConcurrentMap<String, WebSocketServer> socketConcurrentHashMap =new ConcurrentHashMap<>();
private Session session;
private String idno;
//连接建⽴成功调⽤的⽅法
@OnOpen
public void onOpen(@PathParam("idno")String idno, Session session){
this.session = session;
this.idno = idno;
this.idno = idno;
socketConcurrentHashMap.put(idno,this);
webSockets.add(this);//加⼊set中
addOnlineCount();
logger.info("有新连接加⼊!当前在线⼈数为"+getOnlineCount());
}
@OnClose
public void onClose(){
if(!idno.equals("")){
}
subOnlineCount();
logger.info("有⼀连接关闭!当前在线⼈数为"+getOnlineCount());
}
@OnMessage
public void onMessage(String message, Session session){
logger.info("client message:"+message);
if(StringUtils.isEmpty(idno)){//发消息
websocket和socketsendAll(message);
}else{//单独推送
if(message.equalsIgnoreCase("ping")){
heartCheck(message);
}else{
sendToUser(message);
}
}
}
private void sendAll(String message){
for(String userId:socketConcurrentHashMap.keySet()){
try{
<(userId).sendMessage(message);
}catch(IOException e){
<("WebSocketServer|sendAll[error]:e={}",e.getMessage());
}
}
}
private void heartCheck(String message){
(idno)!=null){
try{
<(idno).sendMessage(message);
}catch(IOException e){
<("WebSocketServer|heartCheck[error]:e={}",e.getMessage());
}
}
}
private void sendToUser(String message){
(idno)!=null){
for(String userId:socketConcurrentHashMap.keySet()){
if(userId.equals(this.idno)){
continue;
}
try{
<(userId).sendMessage(message);
}catch(IOException e){
<("WebSocketServer|sendToUser[error]:e={}",e.getMessage());
}
}
}
}
@OnError
public void onError(Session session, Throwable e){
public void onError(Session session, Throwable e){
// throwable.printStackTrace();
<("WebSocketServer|onError[error]:e={}",e.getMessage()); }
public static synchronized int getOnlineCount(){
return onlineCount;
}
public static synchronized void addOnlineCount(){
}
public static synchronized void subOnlineCount(){
}
public void sendMessage(String message)throws IOException {
BasicRemote().sendText(message);
//AsyncRemote().sendText(message);
}
}
3.client的实现
import com.alipay.api.java_websocket.client.WebSocketClient;
import com.alipay.api.java_websocket.handshake.ServerHandshake;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.URI;
import java.URISyntaxException;
/**
* socket推送消息(客户端)
*/
public class SocketClient extends WebSocketClient {
private final static Logger logger = Logger(SocketClient.class); public SocketClient(URI serverUri){
super(serverUri);
}
/**
* demo
* @param args
* @throws URISyntaxException
* @throws InterruptedException
*/
public static void main(String[] args)throws URISyntaxException, InterruptedException { String url ="ws://127.0.0.1:8080/socket/websocket/1233435";
SocketClient client =new SocketClient(new URI(url));
Thread.sleep(5000);
System.out.println(client.isOpen());
client.send("哈哈哈哈");
client.close();
}
@Override
public void onOpen(ServerHandshake serverHandshake){
logger.info("SocketClient:------打开socket--------");
}
@Override
public void onMessage(String s){
logger.info("SocketClient:-----接受服务端消息-----"+s);
}
@Override
public void onClose(int i, String s,boolean b){
logger.info("SocketClient:----关闭socket链接");
}
@Override
public void onError(Exception e){
<("SocketClient|onError[error]:e={}",e.getMessage());
}
}
4.websocket鉴权配置类
hk.crm.socket;
fig.Constant;
slf4j.Slf4j;
import org.apachemons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.t.request.RequestContextHolder;
import org.t.request.ServletRequestAttributes;
import javax.servlet.http.HttpServletRequest;
import javax.websocket.HandshakeResponse;
import javax.websocket.server.HandshakeRequest;
import javax.websocket.server.ServerEndpointConfig;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Arrays;
import java.util.List;
/**
* websocketserver 鉴权
*/
@Slf4j
@Component
public class SocketServerConfigurator extends ServerEndpointConfig.Configurator {
private final Logger logger = Logger(SocketServerConfigurator.class);
/**
* token鉴权认证
*
* @param originHeaderValue
* @return
*/
@Override
public boolean checkOrigin(String originHeaderValue){
// 业务判断代码,可以判断⼀些请求参数时候合法
ServletRequestAttributes servletRequestAttributes =(ServletRequestAttributes) RequestAttributes(); String whiteUser = Constant.("websocket_white_user");
try{
HttpServletRequest request = Request();
String url = ServletPath();
if(StringUtils.isBlank(url)){
return false;
}
String phone = url.substring(url.lastIndexOf("/")+1);
logger.info("SocketServerConfigurator|checkOrigin:phone="+ phone);
ains(phone)){
return super.checkOrigin(originHeaderValue);
}else{
return false;
}
}catch(Exception e){
<("SocketServerConfigurator|checkOrigin[ERROR]:e={}", e);
return false;
}
}
/**
* Modify the WebSocket handshake response
* 修改websocket 返回值
*
* @param sec
* @param request
* @param response
*/
@Override
public void modifyHandshake(ServerEndpointConfig sec, HandshakeRequest request, HandshakeResponse response){
}
}
以上就很简单的实现类⼀个websocket服务的创建和client请求demo,以供参考。
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。
发表评论