socket建立及nginx負載均衡(TCP反向代理非HTTP代理)

NGINX 編譯須要加這兩個模塊,纔可進行tcp代理轉發python

--with-stream --with-stream_ssl_modulenginx

 

nginx.conf(stream須要跟http同級)socket

stream {tcp

    upstream stream_backend {線程

        server 127.0.0.1:2401 weight=5;代理

        server 127.0.0.1:2402 weight=5;code

    }server

    server {utf-8

        listen     2403;ssl

        proxy_pass stream_backend;

    }

}

http{

}

 

服務端:

python socket_server_test.py 127.0.0.1 2401

python socket_server_test.py 127.0.0.1 2402

#!/usr/bin/python

import socket

import threading

import time

import sys

 

def tcplink(sock, addr):

    print('Accept new connection from %s:%s...' % addr)

    sock.send(b'Welcome!')

    while True:

        data = sock.recv(1024)

        time.sleep(1)

        if not data or data.decode('utf-8') == 'exit':

            break

        sock.send(('Hello, %s!' % data.decode('utf-8')).encode('utf-8'))

    sock.close()

    print('Connection from %s:%s closed.' % addr)

 

if __name__ == '__main__':

if len(sys.argv) < 3:

print('Usage: %s [hostname] [port number]' %sys.argv[0])

sys.exit(1)

hostname = sys.argv[1]

port = int(sys.argv[2])

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

# 監聽端口:

s.bind((hostname, port))

s.listen(5)

print('Waiting for connection...')

while True:

    # 接受一個新鏈接:

    sock, addr = s.accept()

    # 建立新線程來處理TCP鏈接:

    t = threading.Thread(target=tcplink, args=(sock, addr))

    t.start()

 

客戶端:

#!/usr/bin/python

import socket

 

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

# 創建鏈接:

s.connect(('xxx,xxx,xx,,xx', 2403))

# 接收歡迎消息:

print(s.recv(1024).decode('utf-8'))

for data in [b'Michael', b'Tracy', b'Sarah', b'Sarah', b'Sarah', b'Sarah', b'Sarah', b'Sarah']:

    # 發送數據:

    s.send(data)

    print(s.recv(1024).decode('utf-8'))

s.send(b'exit')

s.close()

相關文章
相關標籤/搜索