我对Node.js非常陌生,我正在创建一个普通的聊天应用程序,以了解更多有关它的信息。我正在使用ws库
在我的实验中,我发现node.js代码不能直接在浏览器中工作(我更具体地要求())。因此,为了使它在浏览器中工作,我不得不使用browserify,它将代码转换为兼容浏览器。
但是,转换后的代码会引发未定义函数的错误。
我的node.js代码
var WebSocket = require('ws')
, ws = new WebSocket('ws://localhost:8080');
ws.on('open', function() {
var firstMessage = '{"type":"name","message":"god"}';
ws.send(firstMessage.toString());
});
ws.on('message', function(message) {
console.log('received: %s', message);
});我使用browserify转换的代码
(function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(require,module,exports){
/**
* Module dependencies.
*/
var global = (function() { return this; })();
/**
* WebSocket constructor.
*/
var WebSocket = global.WebSocket || global.MozWebSocket;
/**
* Module exports.
*/
module.exports = WebSocket ? ws : null;
/**
* WebSocket constructor.
*
* The third `opts` options object gets ignored in web browsers, since it's
* non-standard, and throws a TypeError if passed to the constructor.
* See: https://github.com/einaros/ws/issues/227
*
* @param {String} uri
* @param {Array} protocols (optional)
* @param {Object) opts (optional)
* @api public
*/
function ws(uri, protocols, opts) {
var instance;
if (protocols) {
instance = new WebSocket(uri, protocols);
} else {
instance = new WebSocket(uri);
}
return instance;
}
if (WebSocket) ws.prototype = WebSocket.prototype;
},{}],2:[function(require,module,exports){
var WebSocket = require('ws')
, ws = new WebSocket('ws://localhost:8080');
console.log(ws);
ws.on('open', function() { //line that contains error
var firstMessage = '{"type":"name","message":"Ayush"}';
ws.send(firstMessage.toString());
});
ws.on('message', function(message) {
console.log('received: %s', message);
});
},{"ws":1}]},{},[2]);我的服务器代码
var WebSocketServer = require('ws').Server
, wss = new WebSocketServer({port: 8080});
var index = 0;
var map = {};
wss.on('connection', function(ws) {
map[index] = ws;
var myindex = index;
var username;
index++;
ws.on('message', function(message) {
var json = JSON.parse(message);
if(json.type == "name"){
username = json.message;
console.log(username);
} else {
//Print Message
}
});
ws.send('something');
ws.on('close', function(){
console.log("Deleting index" + myindex);
delete map[myindex];
});
});但是,当我使用浏览器化并使用转换后的代码时,它会在第50行抛出一个错误。
Uncaught :未定义不是ws.open上的函数
发布于 2015-01-25 15:45:30
ws库构建在原始TCP套接字之上。出于安全原因,您不能在客户端JavaScript中使用这些,所以这是行不通的。您需要在浏览器中使用WebSocket构造函数。
唯一能够成功浏览的node.js库是那些没有使用node.js标准库的库--文件系统、网络等等,即underscore和async这样的实用程序库。
https://stackoverflow.com/questions/28135754
复制相似问题