1.nginx 配置
通过配置proxy_protocol on来获取客户端真实ip
stream {
tcp_nodelay on;
upstream socketGm{
hash $remote_addr consistent;
#server 192.168.100.196:6781 weight=5 max_fails=3 fail_timeout=30s;
server 192.168.0.190:30194 weight=5 max_fails=3 fail_timeout=30s;
#server 192.168.0.74:30194;
}
# upstream socketSocsp{
# hash $remote_addr consistent;
#server 192.168.0.198:30193 weight=5 max_fails=3 fail_timeout=30s;
#server 192.168.100.196:6780 weight=5 max_fails=3 fail_timeout=30s;
#server 192.168.0.74:30193;
#}
server{
listen 6578;
proxy_connect_timeout 1s;
proxy_timeout 3s;
#获取客户端ip配置
proxy_protocol on;
proxy_pass socketGm;
}
#server{
# listen 6577;
# proxy_connect_timeout 1s;
# proxy_timeout 3s;
# proxy_protocol on;
# proxy_pass socketSocsp;
#}
}
注意事项 1.当客户端先建立连接的时候后续再发送请求时候,会发送一个请求
#客户端
Socket client = new Socket();
InputStream is = null;
OutputStream os = null;
client.setReuseAddress(true);
client.connect(new InetSocketAddress(ip, port),10*1000);
...
自己逻辑代码 如reqData的生成
...
os = client.getOutputStream();
is = client.getInputStream();
os.write(reqData);
os.flush();
client.shutdownOutput();
#服务端
会先接收到一个52位的头信息
例:PROXY TCP4 192.168.100.141 192.168.0.71 22626 6578
注意事项 2. 当客户端先建立连接的同时发送请求的时候,只会发送一个请求
#客户端伪代码
...
自己逻辑代码 如reqData的生成
...
Socket client = new Socket();
InputStream is = null;
OutputStream os = null;
client.setReuseAddress(true);
client.connect(new InetSocketAddress(ip, port),10*1000);
os = client.getOutputStream();
is = client.getInputStream();
os.write(reqData);
os.flush();
client.shutdownOutput();
注意事项 3. 当使用Socket.shutdownOutput()后,客户端接收不到nginx返回的数据了。
#客户端伪代码
Socket client = new Socket();
out.write(req);
out.flush();
#使用后将接收不到数据
client.shutdownOutput();
DataInputStream in = new DataInputStream(client.getInputStream());
byte[] reply = new byte[280];
in.read(reply);
评论区