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
12345678910111213 |
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, relatively simple do not need to listen, do not need to loop
123456789 |
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()
|
Very simple, haha, you can build on this code to optimize the creation of more powerful features
www.qytang.com/
http://www.qytang.com/cn/list/29/
http://www.qytang.com/cn/list/28/446.htm
http://www.qytang.com/cn/list/28/445.htm
http://www.qytang.com/cn/list/28/444.htm
http://www.qytang.com/cn/list/28/442.htm
http://www.qytang.com/cn/list/28/440.htm
http://www.qytang.com/cn/list/28/437.htm
http://www.qytang.com/cn/list/28/435.htm
http://www.qytang.com/cn/list/28/434.htm
http://www.qytang.com/cn/list/28/433.htm
http://www.qytang.com/cn/list/28/431.htm
http://www.qytang.com/cn/list/28/328.htm
http://www.qytang.com/cn/list/28/326.htm
http://www.qytang.com/cn/list/28/429.htm
Python develops a simple chat tool-The Yi Tang