看到眼前那束光了麼? 再往前一步會看着更明亮
介紹
nginx支持socket轉發嗎?
實話說,我沒做過socket轉發,但是我知道socket跟http一樣都是通過tcp或者udp通信的,我猜測啦一下nginx應該支持吧,然後又在網上查啦一下,網上說支持,也有支持的相關官方文檔,且有理有據,於是我秉承不瞎扯,知之爲知之的科學態度,我只對網友回啦兩個字:“可以”.
前10分鐘,先寫一個socket的服務端與客戶端可以通信
實現服務端可以向客戶端發送信息,客戶端接受到信息後,顯示出來。用c#控制檯程序實現。
服務端監聽本機ip與端口,服務端代碼如下:
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("鏈接成功!");
}
}
}
客戶端連接ip爲nginx代理服務器ip,客戶端如下:
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);
}
}
}
中間10分鐘,搭建nginx服務器
準備一臺linux服務器。nginx官網:http://nginx.org/ 。在網上搜到大致用的是 ngx_stream_core_module 這個模塊,這裏你也可以關注一下官方文檔中的其他模塊都是做什麼的,那麼這有相關的啓用配置說明,與示例配置。
第一句便是:該ngx_stream_core_module模塊是自1.9.0版本。此模塊不是默認構建的,應使用配置參數啓用 --with-stream 。
那好吧,我們就安裝nginx,搞這個的,安裝應該都會吧。
[root@localhost /]# cd /usr/local/src
[root@localhost src]# wget http://nginx.org/download/nginx-1.11.10.tar.gz
然後解壓,解壓完,根據文檔提示需要使用這個參數–with-stream 來啓用功能。
[root@localhost src]# ./configure --prefix=/usr/local/nginx --with-stream
然後,make,make install。
完成之後就是nginx配置配置文件啦,這個文檔中有示例,可知與events模塊平級,按照這做就好啦。
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;
}
}
ok,保存退出,重啓nginx使配置生效即可。到這裏所有的操作就都完成啦,讓我們拭目以待,看下結果吧。
最後10分鐘,測試nginx轉發socket結果
啓動服務端—>顯示:開啓監聽—>啓動客戶端----> 客戶端顯示:連接成功---->服務端輸入:abc----->服務端:點擊回車---->客戶端顯示:abc。如下:
服務端:
客戶端
至此所有的都已整個過程都已結束,功能實現。