【发布时间】:2015-03-10 20:11:35
【问题描述】:
我使用 QML 的 WebSockets 组件创建了一个简单的聊天应用程序。这只是客户:
Window {
id: root
visible: true
width: 1024
height: 768
property variant messages: []
WebSocket {
id: sock
url: "http://localhost:3700"
onTextMessageReceived: {
var data = message;
var messages = root.messages;
if(data.message) {
messages.push(data);
var html = '';
for(var i = 0; i < messages.length; i++) {
html += '<b>' + (messages[i].username ? messages[i].username : 'Server') + ': </b>';
html += messages[i].message + '<br />';
}
messageBox.append(html);
} else {
messageBox.append("There is a problem:", data);
}
}
onStatusChanged: {
if (sock.status == WebSocket.Error) {
messageBox.append("Error: " + sock.errorString);
}
else if (sock.status == WebSocket.Open) {
messageBox.append("Socket open");
}
else if (sock.status == WebSocket.Closed) {
messageBox.append("Socket closed");
}
}
active: false
}
使用this 文章在 Node.js 和 Socket.io 上实现服务器。 问题是,当我尝试连接到服务器时,应用程序会抛出这个:
Error: Unsupported WebSocket scheme: http
如果我将协议更改为 ws,则服务器将关闭连接。我能做什么?
服务器代码:
var express = require("express");
var app = express();
var port = 3700;
app.set('views', __dirname + '/tpl');
app.set('view engine', "jade");
app.engine('jade', require('jade').__express);
app.get("/", function(req, res){
res.render("page");
});
app.use(express.static(__dirname + '/public'));
var io = require('socket.io').listen(app.listen(port));
io.sockets.on('connection', function (socket) {
socket.emit('message', { message: 'welcome to the chat' });
socket.on('send', function (data) {
io.sockets.emit('message', data);
});
});
console.log("Listening on port " + port);
【问题讨论】:
-
Socket.io !== websockets。 Socket.io 首先使用 xhr 连接,如果支持,则升级到 websockets。
-
Socket.io 在服务器上,那里没有 xhr。你的意思是我需要创建一个没有 Socket.io 的服务器吗?
-
与 socket.io 的初始连接需要 xhr...
Socket.IO never assumes that WebSocket will just work, because in practice there’s a good chance that it won’t. Instead, it establishes a connection with XHR or JSONP right away, and then attempts to upgrade the connection to WebSocket..