Python is so powerful that it can do anything, haha, a joke. But what we're going to talk about today is really a very magical application.
Use Python to write a chat tool
In fact, we usually use the QQ similar chat tool, is also used to chat with the socket, but it also contains more complex features. The rationale is the same.
Python realizes the chat function, mainly uses the socket module. Let's go directly to the example below.
Server Side
Import Sockets=socket.socket () #建立socket链接s. Bind ((' 127.0.0.1 ', 8000)) #监听连接请求, of which 1 is the listener for a s.listen (1) #进行循环, Listen to the message from the client while 1: #获取链接IP和端口 conn,addr=s.accept () print ' [' +addr[0]+ ': ' +str (addr[1]) + '] Send a message To me: ' +conn.recv (1024x768) Conn.sendall (' I received a message from [' +addr[0]+ ': ' +str (addr[1]) + '] ') s.close ()
Client side, relatively simple do not need to listen, do not need to loop
Import Sockets=socket.socket () #链接s. Connect ((' 127.0.0.1 ', 8000)) #获取键盘输入msg = raw_input ("Please input your message:") S.sendall (msg) print s.recv (1024x768) s.close ()
Very simple, haha, you can build on this code to optimize the creation of more powerful features