parent
aca391e3a8
commit
3564cf1bd0
File diff suppressed because one or more lines are too long
@ -0,0 +1,16 @@ |
||||
package com.hai.config; |
||||
|
||||
import org.springframework.context.annotation.Bean; |
||||
import org.springframework.stereotype.Component; |
||||
import org.springframework.web.socket.server.standard.ServerEndpointExporter; |
||||
|
||||
|
||||
@Component |
||||
public class WebSocketConfig { |
||||
|
||||
@Bean |
||||
public ServerEndpointExporter serverEndpointExporter() { |
||||
return new ServerEndpointExporter(); |
||||
} |
||||
|
||||
} |
@ -0,0 +1,67 @@ |
||||
package com.hai.service; |
||||
|
||||
import org.slf4j.Logger; |
||||
import org.slf4j.LoggerFactory; |
||||
import org.springframework.stereotype.Component; |
||||
|
||||
import javax.websocket.*; |
||||
import javax.websocket.server.PathParam; |
||||
import javax.websocket.server.ServerEndpoint; |
||||
import java.io.IOException; |
||||
import java.util.HashMap; |
||||
import java.util.Map; |
||||
|
||||
@Component |
||||
@ServerEndpoint("/WebSocket/{userId}") |
||||
public class WebSocket { |
||||
private static Logger log = LoggerFactory.getLogger(WebSocket.class); |
||||
/** |
||||
* 在线用户,将其保存在set中,避免用户重复登录,出现多个session |
||||
*/ |
||||
private static final Map<String, Session> USERS = new HashMap<>(); |
||||
|
||||
//连接时执行
|
||||
@OnOpen |
||||
public void onOpen(@PathParam("userId") String userId, Session session) throws IOException { |
||||
if (userId != null) { |
||||
USERS.put(userId , session); |
||||
} |
||||
System.out.println("【WebSocket消息】有新的连接" + userId); |
||||
} |
||||
|
||||
//关闭时执行
|
||||
@OnClose |
||||
public void onClose() { |
||||
System.out.println("【WebSocket消息】断开连接"); |
||||
} |
||||
|
||||
//收到消息时执行
|
||||
@OnMessage |
||||
public void onMessage(String message) throws IOException { |
||||
log.debug("【WebSocket消息】收到客户端发来的信息,总数:{}", message); |
||||
} |
||||
|
||||
//连接错误时执行
|
||||
@OnError |
||||
public void onError(Throwable error) { |
||||
log.debug("【WebSocket消息】收到客户端发来的信息,总数:{}"); |
||||
error.printStackTrace(); |
||||
} |
||||
|
||||
// 给制定用户发送信息
|
||||
public void SenderMessage(String userId , String message) { |
||||
Session sessionUser = USERS.get(userId); |
||||
try { |
||||
sessionUser.getBasicRemote().sendText(message); |
||||
} catch (IOException e) { |
||||
e.printStackTrace(); |
||||
} |
||||
} |
||||
|
||||
// 断开制定用户
|
||||
public void closUser(String userId ) { |
||||
USERS.remove(userId); |
||||
System.out.println("【WebSocket消息】断开连接"); |
||||
} |
||||
|
||||
} |
Loading…
Reference in new issue