这是第一版,最简单的,仅仅实现了通信,你收我发,我收你发而已。下篇将介绍,基于异步多线程的聊天室:
客户端:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
|
#-*-coding:utf-8-*- #聊天室,服务端代码 import socket
soc_object = socket.socket();
address = ( '127.0.0.1' , 9999 )
soc_object.bind(address); soc_object.listen( 2 );
tag = True ;
while tag:
client_object,client_address = soc_object.accept(); #等待连接
print 'Your Friend Online' ;
while True :
content = raw_input ( 'Your Send Content:' );
client_object.send(content);
recontent = client_object.recv( 1024 ); #接收回复
print recontent;
if recontent = = 'exit' :
print 'Session Over'
break ;
soc_object.close(); |
客户端:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
|
#-*-coding:utf-8-*- #聊天室,客户端代码 import socket
soc_object = socket.socket();
address = ( '127.0.0.1' , 9999 )
soc_object.connect(address); while True :
print soc_object.recv( 1024 ) #接收消息
content = raw_input ( 'Your Send Content:' )
soc_object.send(content);
soc_object.close(); |
原文地址:http://rexyan.cn/article/24
Rex博客保留所有权利