我正在尝试使用websockets将在Web浏览器中运行的客户端连接到服务器。
我的客户端是用javascript编写的,而我的服务器是node.js。我已经设法将node.js客户端连接到服务器,但是似乎无法将javascript客户端连接到服务器。
服务器代码:
textfield.setOnKeyPressed(new EventHandler<KeyEvent>() {
@Override
public void handle(KeyEvent event) {
if (event.getCode() == KeyCode.ENTER) {
String text = textarea.getText();
Labeled errorText = null;
if (textfield.getText() != null && !textfield.getText().isEmpty()) {
index = textarea.getText().indexOf(textfield.getText());
textarea.getText();
if (index == -1) {
errorText.setText("Search key Not in the text");
} else {
// errorText.setText("Found");
textarea.selectRange(index, index + textfield.getLength());
}
}
}
}
});
客户代码:
var webSocketServer = require("websocket").server;
var http = require("http");
var port = 9000;
var server = http.createServer(function (request, response) {
console.log(new Date() + " Received request");
});
server.listen(port, function () {
console.log(new Date() + " listening on port 9000");
});
var socket = new webSocketServer({
httpServer: server
});
socket.on("request", function (request) {
var connection = request.accept(null, request.origin);
connection.on("message", function (message) {
console.log(message.utf8Data);
});
});
我希望从运行服务器的命令提示符中看到客户端输出的握手。这不会发生。在浏览器控制台中,我最终收到此错误:
var client = new WebSocket("ws://localhost:9000");
client.onopen = function () {
client.send("Handshake from client");
}
我尝试WebSocket connection to 'ws://localhost:9000/' failed: WebSocket opening handshake timed out
我的客户对象,结果是这样的:
console.log
据我所知,对象是正确构建的,指向正确的URL,但仍然无法建立连接。