我喜欢 Prasanth 的建议,它对我很有效。这是我的代码。
RCP:
logger = ...
private void startJSConsole() {
jsConsoleJob = new Job("JS Console Server") {
@Override
protected IStatus run(IProgressMonitor monitor) {
Socket connectionSocket = null;
try {
jsSocket = new ServerSocket(6789);
while (!monitor.isCanceled()) {
connectionSocket = jsSocket.accept();
readSocketData(connectionSocket);
}
} catch (IOException e) {
if (!"Socket closed".equals(e.getMessage())) {
logger.logError("Unable to open or read from Javascript console server socket", e);
}
return Status.CANCEL_STATUS;
} finally {
try {
if (jsSocket != null) {
jsSocket.close();
}
if (connectionSocket != null) {
connectionSocket.close();
}
} catch (IOException e) {
//pass
}
}
return Status.OK_STATUS;
}
};
jsConsoleJob.setUser(false);
jsConsoleJob.setSystem(true);
jsConsoleJob.schedule();
}
//I copied this code from here: http://stackoverflow.com/a/21729100/2036650
private void readSocketData(Socket connectionSocket) {
try {
BufferedReader in = new BufferedReader(new InputStreamReader(connectionSocket.getInputStream()));
// read request
String line;
line = in.readLine();
StringBuilder raw = new StringBuilder();
raw.append("" + line);
boolean isPost = line.startsWith("POST");
int contentLength = 0;
while (!(line = in.readLine()).equals("")) {
raw.append('\n' + line);
if (isPost) {
final String contentHeader = "Content-Length: ";
if (line.startsWith(contentHeader)) {
contentLength = Integer.parseInt(line.substring(contentHeader.length()));
}
}
}
StringBuilder body = new StringBuilder();
if (isPost) {
int c = 0;
for (int i = 0; i < contentLength; i++) {
c = in.read();
body.append((char) c);
}
}
raw.append(body.toString());
System.err.println("JS: " + body.toString());
connectionSocket.close();
} catch (Exception e) {
e.printStackTrace();
}
}
Javascript:
<html>
<head>
...
<script>
var global = global || {};
global.consoleLog = function(msg) {
var xhttp = new XMLHttpRequest();
xhttp.open("POST", "http://localhost:6789", true);
xhttp.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
xhttp.send(msg);
}
</script>
<script src="js/sigplot-minimized.js"></script>
</head>
<body>
...
</body>
</html>
然后从 Javascript 代码中的任何地方:
global.consoleLog(logMessage);