Python is so powerful that it can do everything. haha, just kidding. But what we want to talk about today is really a magical application. Python is so powerful that it can do everything. haha, just kidding. But what we want to talk about today is really a magical application.
Use python to write a chat tool
In fact, we usually use QQ chat tools similar to socket chat, but it also contains more complex functions. The basic principle is the same.
Python implements the chat function and mainly uses the socket module. Go directly to the instance below
Server
Import sockets = socket. socket () # establish socket link s. bind ('2017. 0.0.1 ', 8000) # listen for connection requests. 1 of them refers to listening for a second. listen (1) # loop, always listen to messages sent from the client while 1: # get the link IP address and port conn, addr = s. accept () print '[' + addr [0] + ':' + str (addr [1]) + '] send a message to me:' + conn. recv (1, 1024) conn. sendall ('I have ed a message from [' + addr [0] + ':' + str (addr [1]) + ']') s. close ()
Client, relatively simple, no listening, no loop
Import sockets = socket. socket () # Link s. connect ('2017. 0.0.1 ', 8000) # obtain the keyboard input msg = raw_input ("Please input your message:") s. sendall (msg) print s. recv (1024) s. close ()
It's easy. haha, you can optimize and create stronger functions based on this code.