var socket = new WebSocket('ws://' + window.location.host + '/my-websocket-endpoint');
// Add an event listener for when a connection is open
socket.onopen = function() {
console.log('WebSocket connection opened. Ready to send messages.');
// Send a message to the server
socket.send('Hello, from WebSocket client!');
};
// Add an event listener for when a message is received from the server
socket.onmessage = function(message) {
console.log('Message received from server: ' + message);
};
public class MyMessageHandler extends TextWebSocketHandler {
@Override
public void afterConnectionClosed(WebSocketSession session, CloseStatus status) throws Exception {
// The WebSocket has been closed
}
@Override
public void afterConnectionEstablished(WebSocketSession session) throws Exception {
// The WebSocket has been opened
// I might save this session object so that I can send messages to it outside of this method
// Let's send the first message
session.sendMessage(new TextMessage("You are now connected to the server. This is the first message."));
}
@Override
protected void handleTextMessage(WebSocketSession session, TextMessage textMessage) throws Exception {
// A message has been received
System.out.println("Message received: " + textMessage.getPayload());
}
}
@Configuration
@EnableWebSocket
public class WebsocketConfig implements WebSocketConfigurer {
@Bean
public WebSocketHandler myMessageHandler() {
return new MyMessageHandler();
}
@Override
public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) {
registry.addHandler(myMessageHandler(), "/my-websocket-endpoint");
}
}
机械节能产品生产企业官网模板...
大气智能家居家具装修装饰类企业通用网站模板...
礼品公司网站模板
宽屏简约大气婚纱摄影影楼模板...
蓝白WAP手机综合医院类整站源码(独立后台)...苏ICP备2024110244号-2 苏公网安备32050702011978号 增值电信业务经营许可证编号:苏B2-20251499 | Copyright 2018 - 2025 源码网商城 (www.ymwmall.com) 版权所有