我想远程管理用户打开的浏览器窗口,以便支持我的网站上的用户。我通过套接字传输点击和键盘事件来模拟一些事件,但由于浏览器
我想远程管理用户打开的浏览器窗口,以便支持我的网站上的用户。
我通过套接字传输点击和键盘事件模拟了一些事件,但由于浏览器策略,我无法访问所有事件。例如,当我想打开颜色选择器时,我收到了一条警告消息。
function triggerClickEvent(clickPosition) {
var { x, y } = clickPosition;
if (!window.clickEvent) {
window.clickEvent = new MouseEvent('click', {
view: window,
bubbles: true,
button: 1,
cancelable: true,
clientX: x,
clientY: y
});
} else {
window.clickEvent.clientX = x;
window.clickEvent.clientY = y;
}
document.elementFromPoint(x, y).dispatchEvent(clickEvent);
clickEvent.target.blur();
clickEvent.target.focus();
clickEvent.target.click();
}
function triggerKeyPressEvent(keyPress) {
var keyPressEvent = new KeyboardEvent('keydown', { 'key': keyPress.key });
document.dispatchEvent(keyPressEvent);
}
如何通过获取相关的用户权限来解决这些问题?
因此,我创建了一个简单的服务器,它使用 ServerSocket 接受来自浏览器的连接。当浏览器连接时,它会运行一个新线程 (ClientHandler) 来处理该连接。在 clientHandler 中,它
所以我创建了一个简单的服务器,它使用 ServerSocket 接受来自浏览器的连接。当浏览器连接时,它会运行一个新线程 (ClientHandler) 来处理该连接。在 clientHandler 中,它响应 GET 请求并提交一个 html 页面。该页面只有 1 个按钮,用于发送值为“Hello from browser”的 POST 请求,这是使用 AJAX 完成的,因此页面不会刷新。每次我发送 POST 请求时,它都会与套接字建立新连接,但响应中的连接是否保持活动状态?
import java.io.*;
import java.net.*;
public class Server {
private static final int PORT = 8080;
private static int count = 0;
private static final String HTML_FILE_PATH = "src/main/java/org/example/index.html";
public static void main(String[] args) throws Exception {
try (ServerSocket serverSocket = new ServerSocket(PORT)) {
System.out.println("Server started on port " + PORT);
while (true) {
try {
Socket clientSocket = serverSocket.accept();
System.out.println("Client: " + ++count + " Joined");
ClientHandler clientHandler = new ClientHandler(clientSocket);
// Handle the client connection in a new thread
new Thread(clientHandler).start();
} catch (IOException e) {
System.err.println("Error accepting client connection: " + e.getMessage());
}
}
}
}
}
import java.io.*;
import java.net.*;
import java.nio.file.Files;
import java.util.concurrent.atomic.AtomicInteger;
public class ClientHandler implements Runnable {
private static final AtomicInteger nextId = new AtomicInteger(0);
private Socket clientSocket;
private int clientId;
private static final String HTML_FILE_PATH = "src/main/java/org/example/index.html";
public ClientHandler(Socket clientSocket) {
this.clientSocket = clientSocket;
this.clientId = nextId.incrementAndGet();
}
@Override
public void run() {
try (BufferedReader reader = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(clientSocket.getOutputStream()))) {
String line;
StringBuilder requestBuilder = new StringBuilder();
while (!(line = reader.readLine()).isBlank()) {
requestBuilder.append(line).append("\r\n");
}
String request = requestBuilder.toString();
String[] requestLines = request.split("\r\n");
String[] requestLine = requestLines[0].split(" ");
String method = requestLine[0];
String path = requestLine[1];
if ("GET".equals(method) && "/".equals(path)) {
serveFile(HTML_FILE_PATH, writer);
} else if ("POST".equals(method)) {
// Extract the Content-Length from the headers
int contentLength = getContentLength(requestLines);
char[] buffer = new char[contentLength];
// Read the POST data from the input stream
reader.read(buffer, 0, contentLength);
String postData = new String(buffer);
// Print the POST data in the server terminal
System.out.println("POST Data: " + postData);
// Continue with sending the response
String responseMessage = "Hello Client " + clientId + ", This is server.";
writeResponse(writer, "HTTP/1.1 200 OK", "text/plain", responseMessage.getBytes(), true);
} else {
writeResponse(writer, "HTTP/1.1 404 Not Found", "text/plain", "Not Found".getBytes(), false);
}
} catch (IOException e) {
System.err.println("Error handling client " + clientId + ": " + e.getMessage());
}
}
private void serveFile(String filePath, BufferedWriter writer) throws IOException {
File file = new File(filePath);
if (file.exists()) {
byte[] fileContent = Files.readAllBytes(file.toPath());
writeResponse(writer, "HTTP/1.1 200 OK", "text/html", fileContent, true);
} else {
writeResponse(writer, "HTTP/1.1 404 Not Found", "text/plain", "File not found".getBytes(), false);
}
}
private void writeResponse(BufferedWriter writer, String statusLine, String contentType, byte[] content, boolean keepAlive) throws IOException {
writer.write(statusLine + "\r\n");
writer.write("Content-Type: " + contentType + "\r\n");
writer.write("Content-Length: " + content.length + "\r\n");
if (keepAlive) {
writer.write("Connection: keep-alive\r\n");
writer.write("Keep-Alive: timeout=60, max=100\r\n");
} else {
writer.write("Connection: close\r\n");
}
writer.write("\r\n");
writer.write(new String(content));
writer.flush();
}
private int getContentLength(String[] requestHeaders) {
for (String header : requestHeaders) {
if (header.toLowerCase().startsWith("content-length:")) {
return Integer.parseInt(header.substring("content-length:".length()).trim());
}
}
return 0;
}
}
<!DOCTYPE html>
<html>
<head>
<title>Tic-Tac-Toe</title>
</head>
<body>
<button id="helloButton">Say Hello</button>
<div id="responseText"></div>
<script>
document.getElementById('helloButton').onclick = function() {
fetch('/', {
method: 'POST',
headers: {
'Content-Type': 'text/plain'
},
body: 'Hello from browser'
})
.then(response => response.text())
.then(data => document.getElementById('responseText').innerText = data)
.catch(error => console.error('Error:', error));
};
</script>
</body>
</html>