java连接websocket服务器并发送消息
一、用python快速启动一个websocker服务器
import tornado.ioloop
import tornado.web
import tornado.websocket
class 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;
@ClientEndpoint
public 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","来自火星");
}
}