Python-based TCP implementation of small robot chat function

Source: Internet
Author: User
This article mainly describes the Python based TCP implementation will chat small robot function, here to share to everyone, the need for friends can refer to the next

The examples in this article describe the small robot functions that python can chat with based on TCP implementations. Share to everyone for your reference, as follows:

A code

1. Service-Side procedures

Import Socketwords ={' How is it ': ' Fine,thank you ', ' How's old was You ': ' The ' What's your name? ': ' Dong Fuguo ', ' What ' yo ur name? ": ' Dong Fuguo ', ' Where does work? ': ' Sdibt ', ' Bye ': ' bye '}host = ' ' PORT =50007s = Socket.socket (Socket.af_inet, Socket. SOCK_STREAM) #绑定sockets. Bind ((HOST, Port)) #开始监听s. Listen (1) print (' Listening at PORT: ', port) conn, addr = S.accept () Print (' Connected by ', addr) while True:  data = CONN.RECV (1024x768)  data = Data.decode ()  ifnot data:breakprint (' Received message: ', Data ' Conn.sendall (words.get (data, ' nothing '). Encode ()) Conn.close ()

2. Client program

Import sockethost = ' 127.0.0.1 ' #服务端主机IP地址PORT =50007# server-side host port number 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 (1024x768) #从客户端接收数据  data = Data.decode ()  print (' Received: ', data)  if C.lower () = = ' Bye ': Breaks.close () #关闭连接

Two running results

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.