import javax.websocket.*;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
@ServerEndpoint("/ws/echo")
public class EchoEndpoint {
@OnOpen
public void onOpen(Session session) throws IOException {
session.getBasicRemote().sendText("CONNECTED: " + session.getId());
}
@OnMessage
public void onMessage(String msg, Session session) throws IOException {
session.getBasicRemote().sendText("ECHO: " + msg);
}
@OnClose
public void onClose(Session session, CloseReason cr) {
System.out.println("CLOSED: " + cr);
}
@OnError
public void onError(Session session, Throwable t) {
t.printStackTrace();
}
}
const ws = new WebSocket("ws://localhost:8080/yourapp/ws/echo");
ws.onopen = () => ws.send("Hello");
ws.onmessage = e => console.log("recv:", e.data);
ws.onclose = () => console.log("closed");
import javax.websocket.*;
import javax.websocket.server.ServerEndpointConfig;
import java.util.Collections;
import java.util.HashSet;
import java.util.Set;
public class MyAppConfig implements ServerApplicationConfig {
@Override
public Set<Class<?>> getAnnotatedEndpointClasses(Set<Class<?>> scanned) {
return scanned; // 扫描到的 @ServerEndpoint 类
}
@Override
public Set<ServerEndpointConfig> getEndpointConfigs(Set<Class<? extends Endpoint>> scanned) {
Set<ServerEndpointConfig> cfgs = new HashSet<>();
cfgs.add(ServerEndpointConfig.Builder.create(MyEndpoint.class, "/ws/prog").build());
return cfgs;
}
}
@javax.websocket.ClientEndpoint
class MyEndpoint extends Endpoint {
@Override
public void onOpen(Session session, EndpointConfig config) {
session.addMessageHandler(new MessageHandler.Whole<String>() {
@Override public void onMessage(String text) {
try { session.getBasicRemote().sendText("ACK:" + text); }
catch (IOException e) { e.printStackTrace(); }
}
});
}
}
ClientEndpointConfig cfg = ClientEndpointConfig.Builder.create()
.configurator(new ClientEndpointConfig.Configurator() {
@Override
public void beforeRequest(Map<String,List<String>> headers) {
// 可添加自定义请求头
}
})
.build();
cfg.getUserProperties().put("org.apache.tomcat.websocket.IO_TIMEOUT_MS", "10000");
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。