2015-01-25 3 views
0

저는 Node.js를 처음 사용하고 그것에 대해 자세히 알기 위해 일반적인 채팅 응용 프로그램을 만들고있었습니다. 나는 ws 라이브러리를 사용하고있다.node.js 코드가 브라우저에서 작동하도록 만들기

내 실험에서 node.js 코드가 브라우저에서 직접 작동하지 않는다는 것을 발견했다. 그래서 브라우저에서 작동하게하려면 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]); 

을 browserify하여 코드 변환

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); 
}); 

내 Node.js를 코드

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]; 
    }); 
}); 
+0

로컬 변수로 전역'WebSocket'을 음영 처리하는 것이 문제를 일으킬 수 있습니다. 'var WebSocket = require ('ws'), ws = new WebSocket (..)을'var WS = require ('ws'), ws = new WS (..)와 같이 변경하려고 시도 했습니까? – mscdex

답변

0

ws 라이브러리를 기반으로 구축되어 ws.open의 기능 아닌 정의되지 않은 : 내가 browserify를 사용하여 내 변환 된 코드를 사용하는 경우그러나, 그것은 라인에서 50

catch되지 않은 형식 오류를 오류가 발생합니다 원시 TCP 소켓. 보안상의 이유로 클라이언트 쪽 JavaScript에서 사용할 수 없으므로 작동하지 않습니다. 브라우저에서 WebSocket 생성자를 사용해야합니다.

성공적으로 탐색 할 node.js 라이브러리는 node.js 표준 라이브러리 (파일 시스템, 네트워킹 등)를 사용하지 않는 라이브러리 즉, underscoreasync과 같은 유틸리티 라이브러리입니다.

관련 문제