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