一、用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","来自火星");
}
}
文章来源地址https://www.toymoban.com/news/detail-673454.html
文章来源:https://www.toymoban.com/news/detail-673454.html
到了这里,关于java连接websocket服务器并发送消息的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!