Skip to content

Instantly share code, notes, and snippets.

@yueyuzhao
Created August 28, 2018 13:06
Show Gist options
  • Save yueyuzhao/c469207dcf8e8c02a9525415deb4bf08 to your computer and use it in GitHub Desktop.
Save yueyuzhao/c469207dcf8e8c02a9525415deb4bf08 to your computer and use it in GitHub Desktop.
代理翻墙 (nodejs实现)
// 客户端实现
const net = require('net')
const tls = require('tls')
const localServer = new net.Server()
localServer.on('connection', (socket) => {
socket.pause()
const context = {
family: 4, // 使用IPv4
rejectUnauthorized: false, // 如果使用自己签发的证书的话,得加上这个配置
}
// 将across.local替换为你自己的域名,并设置好解析
// 通过tls连接远程服务器
const remoteSocket = tls.connect(37637, 'across.local', context, () => {
socket.pipe(remoteSocket)
remoteSocket.pipe(socket)
socket.resume()
})
remoteSocket.on('error', (e) => {
console.log(e)
socket.end()
})
socket.on('error', () => {})
socket.on('end', () => {})
})
// 启动本地服务
localServer.listen(3737)
// 服务器端实现
const fs = require('fs')
const tls = require('tls')
const net = require('net')
const proxy = require('proxy') // 记得将proxy添加到你的package.json依赖中
// 1. 创建一个TLS服务来加密数据 (记得签发你自己的证书)
const options = {
key: fs.readFileSync('./keys/across.key'),
cert: fs.readFileSync('./keys/across.pem'),
}
const server = tls.createServer(options, (socket) => {
socket.pause()
// 连接并转发数据到本机的代理服务器
const remoteSocket = net.connect(3738, '127.0.0.1', () => {
socket.pipe(remoteSocket)
remoteSocket.pipe(socket)
socket.resume()
})
socket.on('error', () => {})
socket.on('end', () => {})
})
// 2. 创建一个本机的代理服务器(站在巨人的肩膀上)
const proxyServer = proxy()
proxyServer.listen(3738, '127.0.0.1', () => {
const port = proxyServer.address().port
console.log('proxy server listening on port %d', port)
})
// 3. 启动TLS服务
server.listen(37637, () => {
console.log('server bound 37637')
})
{
"name": "across",
"version": "1.0.0",
"main": "across.server.js",
"license": "MIT",
"dependencies": {
"proxy": "^0.2.4"
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment