Python使用TCP實現簡單對話

NewDay_發表於2020-10-06

注意:需要先啟動伺服器,在啟動客戶端

TCP server

import socket
from os.path import commonprefix

words = {
    'how are you?':"Fine thank you",
    'how old are you?':'38',
    'what is your name?':'Ji Ruan',
    "what's your name?":"Ji Ruan",
    'where do you work?':'Nan Yang',
    'bey':'Bye'
}
HOST = ''
PORT = 50007
s = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
#繫結socket
s.bind((HOST,PORT))
#開始監聽一個客戶端連線
s.listen(1)
print("Linsten on port :" ,PORT)
#阻塞等待客戶端連線
conn,addr = s.accept()
print("Connected by",addr)
#開始聊天
while True:
    data = conn.recv(512).decode()#解碼
    if not data:
        break
    print("Received message:",data)
    # 儘量猜測對方要表達的真正意思
    m = 0
    key = ''
    for k in words.keys():
        #刪除多餘的空白字元
        data = ' '.join(data.split())
        # 與某個 鍵接近,就直接返回
        if len(commonprefix([k,data])) > len(k)* 0.7:
            key = k
            break
            # 使用選擇發,選擇一個重合度交的鍵
        length = len(set(data.split()) & set(k.split()))
        if length > m:
            m = length
            key = k
    #選擇適合資訊進行回覆
    conn.sendall(words.get(key, 'Sorrey.').encode())
conn.close()
s.close()


TCP cilent

import socket
import sys
#服務端主機IP地址,和埠號
HOST = '127.0.0.1'
PORT = 50007
s =socket.socket(socket.AF_INET,socket.SOCK_STREAM)

try:#異常處理,當伺服器未開啟或者IP錯誤提示
    #連線伺服器
    s.connect((HOST, PORT))
except Exception as e:
    print("Server not found or not open")
    print(e)
    sys.exit()

while True:
    c = input("Input the content you want to send:")
    #傳送資料
    s.sendall(c.encode())
    #從伺服器接收資料
    data = s.recv(512)
    data = data.decode()
    print("Received:" ,data)
    if c.lower() == 'bey':
        break
#關閉連線
s.close()

執行效果:
在這裡插入圖片描述
在這裡插入圖片描述

相關文章