public static void f1() {
try {
WebSocketContainer container = ContainerProvider.getWebSocketContainer(); // 获取WebSocket连接器,其中具体实现可以参照websocket-api.jar的源码,Class.forName("org.apache.tomcat.websocket.WsWebSocketContainer");
String uri = "ws://localhost:8081/log/log";
Session session = container.connectToServer(Client.class, new URI(uri)); // 连接会话
session.getBasicRemote().sendText("123132132131"); // 发送文本消息
session.getBasicRemote().sendText("4564546");
} catch (Exception e) {
e.printStackTrace();
}
}
@ClientEndpoint
public class Client {
@OnOpen
public void onOpen(Session session) {
System.out.println("Connected to endpoint: " + session.getBasicRemote());
}
@OnMessage
public void onMessage(String message) {
System.out.println(message);
}
@OnError
public void onError(Throwable t) {
t.printStackTrace();
}
}
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Lazy;
import org.springframework.messaging.simp.SimpMessagingTemplate;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
import org.springframework.web.socket.WebSocketHandler;
import org.springframework.web.socket.config.annotation.EnableWebSocket;
import org.springframework.web.socket.config.annotation.WebSocketConfigurer;
import org.springframework.web.socket.config.annotation.WebSocketHandlerRegistry;
import com.gionee.log.client.LogWebSocketHandler;
/**
* 注册普通WebScoket
* @author PengBin
* @date 2016年6月21日 下午5:29:00
*/
@Configuration
@EnableWebMvc
@EnableWebSocket
public class WebSocketConfig extends WebMvcConfigurerAdapter implements WebSocketConfigurer {
@Autowired
@Lazy
private SimpMessagingTemplate template;
/** {@inheritDoc} */
@Override
public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) {
registry.addHandler(logWebSocketHandler(), "/log"); // 此处与客户端的 URL 相对应
}
@Bean
public WebSocketHandler logWebSocketHandler() {
return new LogWebSocketHandler(template);
}
}
import org.springframework.messaging.simp.SimpMessagingTemplate;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.handler.TextWebSocketHandler;
/**
*
* @author PengBin
* @date 2016年6月24日 下午6:04:39
*/
public class LogWebSocketHandler extends TextWebSocketHandler {
private SimpMessagingTemplate template;
public LogWebSocketHandler(SimpMessagingTemplate template) {
this.template = template;
System.out.println("初始化 handler");
}
@Override
protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {
String text = message.getPayload(); // 获取提交过来的消息
System.out.println("handMessage:" + text);
// template.convertAndSend("/topic/getLog", text); // 这里用于广播
session.sendMessage(message);
}
}
public static void main(String[] args) {
try {
WebSocketContainer container = ContainerProvider.getWebSocketContainer();
String uri = "ws://localhost:8081/log/hello/hello/websocket";
Session session = container.connectToServer(Client.class, new URI(uri));
char lf = 10; // 这个是换行
char nl = 0; // 这个是消息结尾的标记,一定要
StringBuilder sb = new StringBuilder();
sb.append("SEND").append(lf); // 请求的命令策略
sb.append("destination:/app/hello").append(lf); // 请求的资源
sb.append("content-length:14").append(lf).append(lf); // 消息体的长度
sb.append("{"name":"123"}").append(nl); // 消息体
session.getBasicRemote().sendText(sb.toString()); // 发送消息
Thread.sleep(50000); // 等待一小会
session.close(); // 关闭连接
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* 启用STOMP协议WebSocket配置
* @author PengBin
* @date 2016年6月24日 下午5:59:42
*/
@Configuration
@EnableWebMvc
@EnableWebSocketMessageBroker
public class WebSocketBrokerConfig extends AbstractWebSocketMessageBrokerConfigurer {
/** {@inheritDoc} */
@Override
public void registerStompEndpoints(StompEndpointRegistry registry) {
System.out.println("注册");
registry.addEndpoint("/hello").withSockJS(); // 注册端点,和普通服务端的/log一样的
// withSockJS()表示支持socktJS访问,在浏览器中使用
}
/** {@inheritDoc} */
@Override
public void configureMessageBroker(MessageBrokerRegistry config) {
System.out.println("启动");
config.enableSimpleBroker("/topic"); //
config.setApplicationDestinationPrefixes("/app"); // 格式前缀
}
}
Controller
@Controller
public class LogController {
private SimpMessagingTemplate template;
@Autowired
public LogController(SimpMessagingTemplate template) {
System.out.println("init");
this.template = template;
}
@MessageMapping("/hello")
@SendTo("/topic/greetings") // 订阅
public Greeting greeting(HelloMessage message) throws Exception {
System.out.println(message.getName());
Thread.sleep(3000); // simulated delay
return new Greeting("Hello, " + message.getName() + "!");
}
}
function connect() {
var socket = new SockJS('/log/hello/hello');
stompClient = Stomp.over(socket);
stompClient.connect({}, function(frame) {
setConnected(true);
console.log('Connected: ' + frame);
stompClient.subscribe('/topic/greetings', function(greeting) {
showGreeting(JSON.parse(greeting.body).content);
});
});
}
function disconnect() {
if (stompClient != null) {
stompClient.disconnect();
}
setConnected(false);
console.log("Disconnected");
}
function sendName() {
var name = document.getElementById('name').value;
stompClient.send("/app/hello", {}, JSON.stringify({
'name' : name
}));
}
机械节能产品生产企业官网模板...
大气智能家居家具装修装饰类企业通用网站模板...
礼品公司网站模板
宽屏简约大气婚纱摄影影楼模板...
蓝白WAP手机综合医院类整站源码(独立后台)...苏ICP备2024110244号-2 苏公网安备32050702011978号 增值电信业务经营许可证编号:苏B2-20251499 | Copyright 2018 - 2025 源码网商城 (www.ymwmall.com) 版权所有