本文实例讲述了Python基于TCP实现会聊天的小机器人功能。分享给大家供大家参考,具体如下:
一 代码
1、服务端程序
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
|
import socket words = { 'how are you?' : 'Fine,thank you.' , 'how old are you?' : '38' , 'what is your name?' : 'Dong FuGuo' , "what's your name?" :'Dong FuGuo', 'where do you work?' : 'SDIBT' , 'bye' : 'Bye' } HOST = '' PORT = 50007 s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) #绑定socket s.bind((HOST, PORT)) #开始监听 s.listen( 1 ) print ( 'Listening at port:' ,PORT) conn, addr = s.accept() print ( 'Connected by' , addr) while True : data = conn.recv( 1024 ) data = data.decode() ifnot data: break print ( 'Received message:' , data) conn.sendall(words.get(data, 'Nothing' ).encode()) conn.close() |
2、客户端程序
1
2
3
4
5
6
7
8
9
10
11
12
13
14
|
import socket HOST = '127.0.0.1' #服务端主机IP地址 PORT = 50007 #服务端主机端口号 s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.connect((HOST, PORT)) #连接连接 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() #关闭连接 |
二 运行结果
希望本文所述对大家Python程序设计有所帮助。
原文链接:https://blog.csdn.net/chengqiuming/article/details/78601140