首页 > 解决方案 > 退出闪亮的应用程序时如何关闭连接

问题描述

当我退出(停止)我的闪亮应用程序时,我使用 websocket 连接制作闪亮的应用程序,并希望关闭连接。我有一个建议,函数on.exit()可以解决我的问题,但我不知道在闪亮的应用程序中在哪里使用它。当应用程序停止时,还有其他方法可以关闭连接吗?

标签: rshiny

解决方案


您可以session$onSessionEnded用于此目的。一旦会话结束,里面的代码就会运行。例如:


library(shiny)

# Define UI for application that draws a histogram
ui <- fluidPage(

    # Application title
    titlePanel("Old Faithful Geyser Data"),

    # Sidebar with a slider input for number of bins 
    sidebarLayout(
        sidebarPanel(
            sliderInput("bins",
                        "Number of bins:",
                        min = 1,
                        max = 50,
                        value = 30)
        ),

        # Show a plot of the generated distribution
        mainPanel(
           plotOutput("distPlot")
        )
    )
)

# Define server logic required to draw a histogram
server <- function(input, output) {

    output$distPlot <- renderPlot({
        # generate bins based on input$bins from ui.R
        x    <- faithful[, 2]
        bins <- seq(min(x), max(x), length.out = input$bins + 1)

        # draw the histogram with the specified number of bins
        hist(x, breaks = bins, col = 'darkgray', border = 'white')
    })
    
    session$onSessionEnded(function() {

        # you can put your code here to close the connection
    })
}

# Run the application 
shinyApp(ui = ui, server = server)


推荐阅读