序言
一网友在群中问, nginx 支持 socket 转发吗?
实话说, 我没做过 socket 转发, 但是我知道 socket 跟 http 一样都是通过 tcp 或者 udp 通信的, 我猜测啦一下 nginx 应该支持吧, 然后又在网上查啦一下, 网上说支持, 也有支持的相关官方文档, 且有理有据, 于是我秉承不瞎扯, 知之为知之的科学态度, 我只对网友回啦两个字:"可以", 就不过多扯, 此时群中也有网友为他解答问题啦, 我就继续干我的活啦, 干活, 干活, 干活, 干活, 没有过多的关注这个问题, 没有过多的关注这个问题.
一小时后, 半天后, 半个月后, 一年后 , 十年后 ...
此去经年, 我又来到群中: 哇靠, 这货竟还在执着于同样的问题, 不停的问:"怎么弄, 怎么弄?" !! 感觉杨过的黯然销魂掌都练成啦, 这个货为什么还没有半点进展. 难道他在参悟天书 5 卷, 准备修仙成佛!
于是我就对此问题产生啦极大的兴趣, 开始搞. 从搞到搞到结束不过 30 分钟, 不过 30 分钟, 搞定, 搞定. 下面的篇幅我会详解整个过程.
说此段子大家勿喷我, 但是我只想对群中的此类网友说:
- class Program
- {
- static Socket sck = null;
- static void Main(string[] args)
- {
- sck = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
- // 监听本机 ip
- IPAddress ip = IPAddress.Parse("172.18.8.196");
- IPEndPoint endPoint = new IPEndPoint(ip, int.Parse("11911"));
- sck.Bind(endPoint);
- sck.Listen(10);
- Console.WriteLine("开启监听!");
- Thread thread = new Thread(JtSocket);
- thread.IsBackground = true;
- thread.Start();
- while (true)
- {
- var msg = Console.ReadLine().Trim();
- if (msg != "")
- {
- byte[] buffer = System.Text.Encoding.ASCII.GetBytes(msg); // 将要发送的数据, 生成字节数组.
- accSck.Send(buffer);
- Console.WriteLine("向客户端发送了:" + msg);
- }
- }
- }
- static Socket accSck = null;
- static void JtSocket()
- {
- while (true)
- {
- accSck = sck.Accept();
- Console.WriteLine("链接成功!");
- }
- }
- }
- class Program
- {
- static Socket clientSocket = null;
- static Thread thread = null;
- static void Main(string[] args)
- {
- clientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
- // 这里联通 nginx 代理服务器地址 ip
- IPAddress ip = IPAddress.Parse("172.18.8.252");
- IPEndPoint endpoint = new IPEndPoint(ip, Convert.ToInt32("11911"));
- clientSocket.Connect(endpoint);
- thread = new Thread(ReceMsg);
- thread.IsBackground = true;
- thread.Start();
- Console.WriteLine("123");
- Console.ReadKey();
- }
- static void ReceMsg()
- {
- while (true)
- {
- byte[] buffer = new byte[1024 1024 2];
- clientSocket.Receive(buffer);
- string ReceiveMsg = System.Text.Encoding.UTF8.GetString(buffer).Substring(0,30);
- Console.WriteLine("接收到数据:" + ReceiveMsg);
- }
- }
- }
- [root@localhost /]# cd /usr/local/src
- [root@localhost src]# wget http://nginx.org/download/nginx-1.11.10.tar.gz
- worker_processes 1;
- #error_log logs/error.log;
- #error_log logs/error.log notice;
- #error_log logs/error.log info;
- #pid logs/nginx.pid;
- events {
- worker_connections 1024;
- }
- stream{
- upstream abc{
- server 172.18.8.196:11911;
- }
- server{
- listen 11911;
- proxy_pass abc;
- }
- }
来源: http://www.bubuko.com/infodetail-2717461.html