Java开发模拟终端ping服务器连通性

WebSSH

转载:https://github.com/NoCortY/WebSSH

简易版实现

1、添加依赖

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-websocket</artifactId>
</dependency>
<dependency>
    <groupId>org.projectlombok</groupId>
    <artifactId>lombok</artifactId>
    <optional>true</optional>
</dependency>
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-test</artifactId>
    <scope>test</scope>
</dependency>

2、前端代码

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>Insert title here</title>
</head>
<body>
<script type="text/javascript">
    var websocket=null
    if('WebSocket' in window){
        //调用service请求,获取信息
        websocket=new WebSocket("ws://localhost:8080/websocket");
    }else{
        alert("该浏览器不支持WebSocket!")
    }
    websocket.onopen=function(event){
        console.log("建立连接!");
    }
    websocket.onclose=function(event){
        console.log("连接关闭!");
    }
    websocket.onmessage=function(event){
        console.log("收到消息!"+event.data);
        //弹窗提醒
        document.getElementById("div").innerHTML += event.data + '<br/>';
    }
    websocket.onerror=function(){
        alert("websocket发生错误!");
    }
    websocket.onbeforeunload=function(){
        websocket.close();
    }
</script>
<h4>模拟ping功能</h4>
<div id="div"></div>
</body>
</html>

3、后端代码
a.WebSocketConfig

package com.example.demo1.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.socket.server.standard.ServerEndpointExporter;

@Configuration
public class WebSocketConfig {

    @Bean
    public ServerEndpointExporter serverEndpointExporter() {
        return new ServerEndpointExporter();
    }

}

b.TestController

package com.example.demo1.controller;

import com.example.demo1.wsservice.WebSocketService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import java.io.BufferedReader;
import java.io.InputStreamReader;

@Slf4j
@Controller
@RequestMapping("/index")
public class TestController {

    @Autowired
    private WebSocketService webSocketService;

    @GetMapping("/test")
    public String test(@RequestParam("ip") String ip) {
        String line = null;
        Process pro = null;
        BufferedReader buf = null;
        try {
            String osName = System.getProperty("os.name");
            if (osName.toLowerCase().contains("windows")){
                pro = Runtime.getRuntime().exec("ping " + ip);
                buf = new BufferedReader(new InputStreamReader(pro.getInputStream(),"GB2312"));
            } else if (osName.toLowerCase().contains("linux")){
                pro = Runtime.getRuntime().exec("ping -c 4 " + ip);
                buf = new BufferedReader(new InputStreamReader(pro.getInputStream(),"UTF-8"));
            }
            while ((line = buf.readLine()) != null){
                webSocketService.sendMessage(line);
            }
        }catch (Exception e){
            log.error("执行ping命令出现异常");
            e.printStackTrace();
        }finally {
            if (null != pro){
                pro.destroy();
            }
        }
        return "hello";
    }

}

c.WebSocketService

package com.example.demo1.wsservice;

import org.springframework.stereotype.Component;

import javax.websocket.OnClose;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.concurrent.CopyOnWriteArraySet;

@Component
@ServerEndpoint("/websocket")
public class WebSocketService {
    private Session session;

    //保存连接
    private static CopyOnWriteArraySet<WebSocketService> webSocketService = new CopyOnWriteArraySet<>();

    /**
     * 建立连接
     * @param session
     */
    @OnOpen
    public void opOpen(Session session) {
        this.session = session;
        webSocketService.add(this);
        System.out.println("有新的连接=============》" + webSocketService.size());
    }

    /**
     * 断开连接
     */
    @OnClose
    public void onClose() {
        webSocketService.remove(this);
        System.out.println("断开连接=============》" + webSocketService.size());
    }

    /**
     * 接收客户端消息
     * @param message
     */
    @OnMessage
    public void onMessage(String message) {
        System.out.println("收到客户端消息" + message);
    }

    /**
     * 发送消息到客户端
     * @param message
     */
    public void sendMessage(String message) {
        try {
            for (WebSocketService webSocketService2 : webSocketService) {
                System.out.println("广播消息----->" + message);

                webSocketService2.session.getBasicRemote().sendText(message);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}

posted @ 2022-07-05 20:57  #码农9527#  阅读(189)  评论(0)    收藏  举报