我编写了一个非常基本的Web程序,它连接到Node JS Web服务器,该服务器将文本打印到浏览器的控制台上。
计算机上的一切都很好但是当我尝试从我的iPhone连接到Web套接字服务器时,它没有连接到它(它连接到http服务器而不连接到ws)
SERVER(节点JS)
app.get ('/', function(req, res){
fs.readFile('ws.html', 'utf8', function(err, text){
res.send(text);
});
});
server.listen(1337, function (){
console.log((new Date()) + " Server is listening on port 1337... ");
});
//creating the websocket server
websock = new WebSocketServer({
httpServer: server
});
//WebSocket Server
websock.on('request', function(request) {
console.log((new Date()) + ' Connection from origin ' + request.origin + '.');
var connection = request.accept(null, request.origin);
var index = clients.push(connection) - 1;
console.log((new Date()) + ' Connection accepted.');
//Incoming message handling
connection.on('message', function(message) {
console.log('Client Says: ' + message.utf8Data);
});
connection.on('close', function (connection){
//close connection
});
});
客户端脚本 $(function(){
var content = $('#content');
var input = $('#input');
var status = $('#status');
window.WebSocket = window.WebSocket || window.MozWebSocket;
if (!window.WebSocket) {
content.html($('<p>', { text: 'Browser doesn\'t '
+ 'support WebSockets.'} ));
input.hide();
$('span').hide();
return;
}
var connection = new WebSocket('ws://127.0.0.1:1337');
connection.onopen = function () {
input.removeAttr('disabled');
status.text('Send a Message:');
};
connection.onerror = function (error) {
content.html($('<p>', { text: 'Connection Error' } ));
};
connection.onmessage = function (message) {
// try to decode json
try {
var json = JSON.parse(message.data);
} catch (e) {
console.log('Invalid Message Text: ', message.data);
return;
}
// handle incoming message
connection.send($('#input').val());
};
input.keydown(function(e) {
if (e.keyCode === 13) {
var msg = $(this).val();
if (!msg) {
return;
}
connection.send(msg);
$(this).val('');
if (myName === false) {
myName = msg;
}
}
});
});
我知道那两个浏览器都支持网络套接字,看不出我做错了什么。任何人都可以看到它有什么问题。
答案 0 :(得分:1)
您正在使用环回地址127.0.0.1而不是服务器地址在客户端上打开套接字。
var connection = new WebSocket('ws://127.0.0.1:1337');