Home > Backend Development > Python Tutorial > Python implements small chatting robot function based on TCP

Python implements small chatting robot function based on TCP

不言
Release: 2018-04-09 14:47:00
Original
2376 people have browsed it

This article mainly introduces the function of a small chatting robot based on Python based on TCP. I will share it with you here. Friends who need it can refer to it.

The example of this article describes the implementation of a small chatting robot based on Python based on TCP. Robot functions. Share it with everyone for your reference, the details are as follows:

One code

1. Server program

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()
Copy after login

2. Client program

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()#关闭连接
Copy after login

Second running result

Related recommendations:

Python’s method of creating a symmetric matrix based on the numpy module

Python is based on time Module method to find program running time



##

The above is the detailed content of Python implements small chatting robot function based on TCP. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template