安装nginx, 并下载对应模块
tar -xzvf nginx-1.2.1.tar.gz
patch -p1 < /path/to/nginx_tcp_proxy_module/tcp.patch
$ ./configure --add-module=/path/to/nginx_tcp_proxy_module
make install
修改nginx.conf文件
tcp {
upstream cluster {
# simple round-robin
server 192.168.10.230:8888;
server 192.168.10.230:8888;
check interval=3000 rise=2 fall=5 timeout=1000 ;
#check interval=3000 rise=2 fall=5 timeout=1000 type=ssl_hello;
#check interval=3000 rise=2 fall=5 timeout=1000 type=http;
#check_http_send "GET / HTTP/1.0\r\n\r\n";
#check_http_expect_alive http_2xx http_3xx;
}
server {
listen 8888;
proxy_pass cluster;
}
}
测试是否连接成功
telnet 127.0.0.1 8888
各服务端tcp代码
const net = require('net');
const PORT = 8888;
const HOST = '192.168.10.231';
var clientHandler = function(socket){
//客户端发送数据的时候触发data事件
socket.on('data', function dataHandler(data) {//data是客户端发送给服务器的数据
console.log(socket.remoteAddress, socket.remotePort, 'send', data.toString());
//服务器向客户端发送消息
socket.write(`server ${HOST} received\n`);
});
//当对方的连接断开以后的事件
socket.on('close', function(){
console.log(socket.remoteAddress, socket.remotePort, 'disconnected');
})
};
//创建TCP服务器的实例
//传入的参数是:监听函数clientHandler
var app = net.createServer(clientHandler);
app.listen(PORT, HOST);
console.log('tcp server running on tcp://', HOST, ':', PORT);
启动 tcp.js
node tcp.js
查看端口号
netstat -antp | grep 8888
网友评论