程序逻辑:导入服务器类 - - >定义主机常量 - - >请求处理类 - - >启动代码 |
1 #! /usr/bin/env python |
2 #服务器程序 |
3 from SocketServer import (TCPServer as TCP, |
4 StreamRequestHandler as SRH) |
5 from time import ctime |
6 |
7 HOST = '' |
8 PORT = 21567 |
9 ADDR = (HOST,PORT) |
10 |
11 class MyRequestHandler(SRH): |
12 def handle( self ): |
13 print '...connected from:' , self .client_address |
14 self .wfile.write( '[%s] %s' % (ctime(), |
15 self .rfile.readline())) |
16 |
17 tcpServ = TCP(ADDR,MyRequestHandler) |
18 print 'waiting for connection...' |
19 tcpServ.serve_forever() |
20 |
= = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = |
1 #! /usr/bin/env python |
2 #客户端程序 |
3 from socket import * |
4 |
5 HOST = '192.168.1.190' |
6 PORT = 21567 |
7 BUFSIZ = 1024 |
8 ADDR = (HOST,PORT) |
9 |
10 while True : |
11 tcpCliSock = socket(AF_INET,SOCK_STREAM) |
12 tcpCliSock.connect(ADDR) |
13 data = raw_input ( '> ' ) |
14 if not data: |
15 break |
16 tcpCliSock.send( '%s\r\n' % data) |
17 data = tcpCliSock.recv(BUFSIZ) |
18 if not data: |
19 break |
20 print data.strip() #剥掉行结束符\r\n |
21 tcpCliSock.close() |
22 |
= = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = |
服务器端运行 |
+ + + + + + + + + + + + + + + + |
[root@dogood core16] # python TsTservs.py |
waiting for connection... |
...connected from : ( '192.168.1.110' , 4601 ) |
...connected from : ( '192.168.1.110' , 4602 ) |
...connected from : ( '192.168.1.110' , 4603 ) |
客户端运行 |
+ + + + + + + + + + + + + + + + |
>>> = = = = = = = = = = = = = = = = = = = = = = = = = = = RESTART = = = = = = = = = = = = = = = = = = = = = = = = = = = |
>>> |
> hello |
[Thu Jan 31 06 : 25 : 22 2013 ] hello |
> nihao |
[Thu Jan 31 06 : 25 : 25 2013 ] nihao |
> |
>>> |