Java前后端结合实现红绿灯效果代码示例
这是一个简单的前后端结合的红绿灯 JAVA 代码示例:
前端代码(HTML/CSS/JavaScript):
<!DOCTYPE html>
<html>
<head>
<meta charset='UTF-8'>
<title>红绿灯</title>
<style>
.light {
width: 50px;
height: 50px;
border-radius: 50%;
margin: 10px;
}
.red {
background-color: red;
}
.yellow {
background-color: yellow;
}
.green {
background-color: green;
}
</style>
</head>
<body>
<div class='light red'></div>
<div class='light yellow'></div>
<div class='light green'></div>
<script src='https://code.jquery.com/jquery-3.5.1.min.js'></script>
<script>
$(document).ready(function() {
setInterval(function() {
$.get('http://localhost:8080/light', function(data) {
$('.light').removeClass('red yellow green');
$('.light').eq(data).addClass(['red', 'yellow', 'green'][data]);
});
}, 1000);
});
</script>
</body>
</html>
后端代码(Java):
import java.io.IOException;
import java.io.OutputStream;
import java.net.InetSocketAddress;
import com.sun.net.httpserver.HttpExchange;
import com.sun.net.httpserver.HttpHandler;
import com.sun.net.httpserver.HttpServer;
public class TrafficLightServer {
public static void main(String[] args) throws Exception {
HttpServer server = HttpServer.create(new InetSocketAddress(8080), 0);
server.createContext('/light', new LightHandler());
server.setExecutor(null);
server.start();
}
static class LightHandler implements HttpHandler {
public void handle(HttpExchange he) throws IOException {
int light = (int) (Math.random() * 3);
String response = Integer.toString(light);
he.sendResponseHeaders(200, response.length());
OutputStream os = he.getResponseBody();
os.write(response.getBytes());
os.close();
}
}
}
这段代码运行后,可以在浏览器中访问 http://localhost:8080/ 来查看红绿灯效果。每隔一秒钟,前端会向后端发送一个 GET 请求,获取当前应该显示的灯的颜色,后端会随机生成一个数字来表示当前应该显示哪个灯,然后将这个数字作为响应返回给前端。前端根据获取到的数字,将对应的灯显示为红、黄或绿色。
原文地址: https://www.cveoy.top/t/topic/ndz2 著作权归作者所有。请勿转载和采集!