【1】Python創建簡單TCP服務器與TCP客戶端

服務器端:

  1. 創建服務器的socket對象
  2. 監聽ip和端口號
  3. 設置最大連接數
  4. 創建一個客服處理線程:接收客戶端發來的數據,再向客戶端發送數據
  5. 開啓線程,等待客戶連接。
# TCPserver.py

import socket
import threading

bind_ip = "0.0.0.0"  #監聽所有可用的接口
bind_port = 51112   #非特權端口號都可以使用

#AF_INET:使用標準的IPv4地址或主機名,SOCK_STREAM:說明這是一個TCP服務器
server = socket.socket(socket.AF_INET,socket.SOCK_STREAM)

#服務器監聽的ip和端口號
server.bind((bind_ip,bind_port))

print("[*] Listening on %s:%d" % (bind_ip,bind_port))

#最大連接數
server.listen(5)

#客戶處理線程
def handle_client(client_socket):

    request = client_socket.recv(1024)

    print("[*] Received: %s" % request)
    #向客戶端返回數據
    client_socket.send("hi~".encode())

    client_socket.close()

while True:

    #等待客戶連接,連接成功後,將socket對象保存到client,將細節數據等保存到addr
    client,addr = server.accept()

    print("[*] Acception connection from %s:%d" % (addr[0],addr[1]))

    client_handler = threading.Thread(target=handle_client,args=(client,))
    client_handler.start()

客戶端:

  1. 創建客戶端socket對象
  2. 用socket對象連接到服務器端(target_host, target_port是服務器端的ip與端口)
  3. 向服務器端發送數據
  4. 從服務器端接收數據
# TCPclient.py

import socket

target_host = "127.0.0.1" #服務器端地址
target_port = 51112  #必須與服務器的端口號一致

while True:

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

    client.connect((target_host,target_port))   

    data = input(">")

    if not data:
        break

    client.send(data.encode())

    response = client.recv(1024)

    print(response)

client.close()
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章