Home > Backend Development > Python Tutorial > Python develops simple chat tools

Python develops simple chat tools

高洛峰
Release: 2016-10-18 10:55:10
Original
1561 people have browsed it

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()
Copy after login

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()
Copy after login

It’s very simple, haha. You can optimize and create stronger products based on this code. Function

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template