// Generated by CoffeeScript 1.7.1
(function() {
  var WebSocketClient, punch, raw, socket, websocket;

  socket = null;

  punch = function(local_port, remote_port, remote_address, _socket) {
    var buffer;
    if (_socket) {
      socket = _socket;
    } else if (!socket) {
      socket = raw.createSocket({
        protocol: raw.Protocol.UDP
      });
    }
    buffer = new Buffer(9);
    buffer.writeUInt16BE(local_port, 0);
    buffer.writeUInt16BE(remote_port, 2);
    buffer.writeUInt16BE(buffer.length, 4);
    return socket.send(buffer, 0, buffer.length, remote_address, function(error, bytes) {
      if (error) {
        throw error;
      }
    });
  };

  if (require.main === module) {
    raw = require('raw-socket');
    WebSocketClient = require("websocket").client;
    websocket = new WebSocketClient();
    websocket.connect("ws://127.0.0.1:5281/", "tunnel");
    websocket.on("connectFailed", function(error) {
      return console.log(error);
    });
    websocket.on("connect", function(connection) {
      console.log(connection);
      connection.on("error", function(error) {
        return console.log(error);
      });
      connection.on("close", function() {
        return console.log('closed');
      });
      return connection.on("message", function(message) {
        var local_port, remote_address, remote_port, _ref;
        if (message.type === "utf8") {
          _ref = message.utf8Data.split(' '), local_port = _ref[0], remote_port = _ref[1], remote_address = _ref[2];
          return punch(parseInt(local_port), parseInt(remote_port), remote_address);
        }
      });
    });
  } else {
    raw = require('nw_raw-socket');
    module.exports = punch;
  }

}).call(this);

//# sourceMappingURL=puncher.map
