網站首頁 編程語言 正文
編寫聊天程序的服務端代碼和客戶端代碼。完成后,先啟動服務端代碼,然 后啟動客戶端程序輸人問題,服務端可以返回相應的答案。要求服務端代碼具 有一定的智能,能夠根據不完整的問題識別客戶端真正要問的問題。 程序運行后界面如下圖所示。
源代碼:
服務端 Sever.py:
from os.path import commonprefix
from posixpath import split
import socket
#建立聊天回復字典
words={'how are you?':'Fine,thank you.',
'how old are you?':'18',
'what is your name?':'xiaoming',
'which subject do you like?':'computer science',
'bye':'Bye'}
s =socket.socket()
s.bind(('127.0.0.1',8000))
s.listen(1)
clientsocket,clientaddress= s.accept()
print('Connection from',clientaddress)
#開始聊天
while True:
data=clientsocket.recv(1024).decode()
if not data:
break
print('Received:',data)
i=0
key=''
for k in words.keys():
data=' '.join(data.split())
if len(commonprefix([k,data]))>len(k)*0.75:
key=k
break
length=len(set(data.split())&set(k.split()))
if length>i:
i=length
key=k
clientsocket.sendall(words.get(key,'Sorry,can\'t find the question').encode())
clientsocket.close()
客戶端 Client.py:
import socket
import sys
s =socket.socket()
try:
s.connect(('127.0.0.1',8000))
except Exception as e:
print('Can\'t find the Sever please try again')
sys.exit()
while True:
c=input('Input the content you want to send:')
s.sendall(c.encode())
data=s.recv(1024)
data=data.decode()
print('Received:',data)
if c.lower()=='bye':
break
s.close()
測試用例:
how are you
how old are you
what's your name
bye
原文鏈接:https://blog.csdn.net/m0_53354306/article/details/124651191
相關推薦
- 2023-01-14 GoLang內存模型詳細講解_Golang
- 2022-06-06 ceph集群RadosGW對象存儲使用詳解_其它綜合
- 2022-11-27 Go?微服務開發框架DMicro設計思路詳解_Golang
- 2024-01-07 Plugin ‘org.springframework.boot:spring-boot-maven
- 2022-12-30 Android入門之在子線程中調用Handler詳解_Android
- 2023-07-09 css樣式重疊解決辦法
- 2022-10-26 Google?Kubernetes?Engine?集群實戰詳解_云其它
- 2022-07-29 C++超詳細講解數組操作符的重載_C 語言
- 最近更新
-
- window11 系統安裝 yarn
- 超詳細win安裝深度學習環境2025年最新版(
- Linux 中運行的top命令 怎么退出?
- MySQL 中decimal 的用法? 存儲小
- get 、set 、toString 方法的使
- @Resource和 @Autowired注解
- Java基礎操作-- 運算符,流程控制 Flo
- 1. Int 和Integer 的區別,Jav
- spring @retryable不生效的一種
- Spring Security之認證信息的處理
- Spring Security之認證過濾器
- Spring Security概述快速入門
- Spring Security之配置體系
- 【SpringBoot】SpringCache
- Spring Security之基于方法配置權
- redisson分布式鎖中waittime的設
- maven:解決release錯誤:Artif
- restTemplate使用總結
- Spring Security之安全異常處理
- MybatisPlus優雅實現加密?
- Spring ioc容器與Bean的生命周期。
- 【探索SpringCloud】服務發現-Nac
- Spring Security之基于HttpR
- Redis 底層數據結構-簡單動態字符串(SD
- arthas操作spring被代理目標對象命令
- Spring中的單例模式應用詳解
- 聊聊消息隊列,發送消息的4種方式
- bootspring第三方資源配置管理
- GIT同步修改后的遠程分支