java连接websocket服务器并发送消息
短信预约 -IT技能 免费直播动态提醒
一、用python快速启动一个websocker服务器
import tornado.ioloopimport tornado.webimport tornado.websocketclass WebSocketHandler(tornado.websocket.WebSocketHandler): def open(self): print("WebSocket 连接已建立") def on_message(self, message): print("收到消息:", message) self.write_message("收到了你的消息:" + message) def on_close(self): print("WebSocket 连接已关闭")def make_app(): return tornado.web.Application([ (r"/websocket", WebSocketHandler), ])if __name__ == "__main__": app = make_app() app.listen(8080) print("WebSocket 服务器已启动,端口号:8080") tornado.ioloop.IOLoop.current().start()
二、使用java连接并发送消息
package com.ciih.iot.common.util;import javax.websocket.*;import java.net.URI;@ClientEndpointpublic class WebSocketClient { @OnOpen public void onOpen(Session session) { System.out.println("Connection established"); try { // 发送一条消息到服务器 session.getBasicRemote().sendText("Hello, WebSocket Server!"); System.out.println("建立连接"); } catch (Exception e) { e.printStackTrace(); } } @OnMessage public void onMessage(String message) { System.out.println("Received message: " + message); } @OnClose public void onClose(Session session, CloseReason reason) { System.out.println("Connection closed: " + reason.getReasonPhrase()); } public static void pushMessage(String url, String message) { try { WebSocketContainer container = ContainerProvider.getWebSocketContainer(); Session session = container.connectToServer(WebSocketClient.class, new URI(url)); session.getBasicRemote().sendText(message); } catch (Exception e) { e.printStackTrace(); } } public static void main(String[] args) { WebSocketClient.pushMessage("ws://localhost:8080/websocket","来自火星"); }}
来源地址:https://blog.csdn.net/wenxingchen/article/details/131580885
免责声明:
① 本站未注明“稿件来源”的信息均来自网络整理。其文字、图片和音视频稿件的所属权归原作者所有。本站收集整理出于非商业性的教育和科研之目的,并不意味着本站赞同其观点或证实其内容的真实性。仅作为临时的测试数据,供内部测试之用。本站并未授权任何人以任何方式主动获取本站任何信息。
② 本站未注明“稿件来源”的临时测试数据将在测试完成后最终做删除处理。有问题或投稿请发送至: 邮箱/279061341@qq.com QQ/279061341