Home >Backend Development >Python Tutorial >Python develops simple chat tools
Python is so powerful that it can do anything, haha, just kidding. But what I’m going to talk about today is really a very magical application.
Use python to write a chat tool
In fact, the QQ-like chat tool that everyone usually uses also uses sockets for chatting, but it also contains more complex functions. The basic principles are the same.
Python implements the chat function, mainly using the socket module. Let’s go directly to the example
server side
import socket s=socket.socket() #建立socket链接 s.bind(('127.0.0.1',8000)) #监听连接请求,其中的1 ,是指监听一个 s.listen(1) #进行循环,一直监听client发来的消息 while 1: #获取链接IP和端口 conn,addr=s.accept() print '['+addr[0]+':'+str(addr[1])+'] send a message to me: '+conn.recv(1024) conn.sendall('I received a message from ['+addr[0]+':'+str(addr[1])+']') s.close()
client side, which is relatively simple and does not require monitoring or looping
import socket s=socket.socket() #链接 s.connect(('127.0.0.1', 8000)) #获取键盘输入 msg = raw_input("Please input your message:") s.sendall(msg) print s.recv(1024) s.close()
It’s very simple, haha. You can optimize and create stronger products based on this code. Function