[Java] 纯文本查看 复制代码 package xman.demo.utils;
import io.netty.handler.codec.http.HttpHeaders;
import io.netty.handler.timeout.IdleStateEvent;
import org.springframework.util.MultiValueMap;
import org.yeauty.annotation.*;
import org.yeauty.pojo.Session;
import java.io.IOException;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
@ServerEndpoint(path = "/ws/{arg}",port = "8088")
public class MyWebSocket {
//用户id=>channel示例
//可以通过用户的唯一标识保存用户的channel
//这样就可以发送给指定的用户
public static Set<Session> clients = new HashSet<>();
/**
* 当有新的连接进入时,对该方法进行回调 注入参数的类型:Session、HttpHeaders...
* [url=home.php?mod=space&uid=952169]@Param[/url] session
* @param headers
* @param req
* @param reqMap
* @param arg
* @param pathMap
*/
@BeforeHandshake
public void handshake(Session session, HttpHeaders headers, @RequestParam String req, @RequestParam MultiValueMap reqMap, @PathVariable String arg, @PathVariable Map pathMap){
session.setSubprotocols("stomp");
if (!"ok".equals(req)){
System.out.println("Authentication failed!");
session.close();
}
}
@OnOpen
public void onOpen(Session session, HttpHeaders headers, @RequestParam String req, @RequestParam MultiValueMap reqMap, @PathVariable String arg, @PathVariable Map pathMap){
System.out.println("new connection");
System.out.println(req);
clients.add(session);
}
@OnClose
public void onClose(Session session) throws IOException {
System.out.println("one connection closed");
clients.remove(session);
}
@OnError
public void onError(Session session, Throwable throwable) {
throwable.printStackTrace();
}
/**
* 当接收到字符串消息时,对该方法进行回调 注入参数的类型:Session、String
* @param session
* @param message
*/
@OnMessage
public void onMessage(Session session, String message) {
clients.forEach(ch -> {
// System.out.println(ch.id().asLongText());
//自己不发送
if(!session.channel().id().asLongText().equals(ch.channel().id().asLongText())){
ch.sendText(message);
}else {
// ch.sendText("自己");
}
});
}
/**
* 当接收到二进制消息时,对该方法进行回调 注入参数的类型:Session、byte[]
* @param session
* @param bytes
*/
@OnBinary
public void onBinary(Session session, byte[] bytes) {
for (byte b : bytes) {
System.out.println(b);
}
session.sendBinary(bytes);
}
/**
* 当接收到Netty的事件时,对该方法进行回调 注入参数的类型:Session、Object
* @param session
* @param evt
*/
@OnEvent
public void onEvent(Session session, Object evt) {
if (evt instanceof IdleStateEvent) {
IdleStateEvent idleStateEvent = (IdleStateEvent) evt;
switch (idleStateEvent.state()) {
case READER_IDLE:
System.out.println("read idle");
break;
case WRITER_IDLE:
System.out.println("write idle");
break;
case ALL_IDLE:
System.out.println("all idle");
break;
default:
break;
}
}
}
}
随便写的,看是不是一样?感觉别人封装好的 应该会好用些
参考 : 调用 ws://127.0.0.1:8088/ws/xman2?req=ok |