VB.net 2010 视频教程 VB.net 2010 视频教程 python基础视频教程
SQL Server 2008 视频教程 c#入门经典教程 Visual Basic从门到精通视频教程
当前位置:
首页 > 编程开发 > Python基础教程 >
  • python基础教程之python-网络编程(4)

服务端:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
#!/use/bin/env python
# -*- coding: utf-8 -*-
 
from SocketServer import (TCPServer as TCP, StreamRequestHandler as SRH)
import time
 
HOST = ''
PORT = 21567
BUFSIZE = 1024
ADDR = (HOST, PORT)
 
#重写SocketServer的子类StreamRequestHandler的handle方法,该方法默认没有任何行为
class MyRequestHandler(SRH):
   def handle(self):
         print '...connected from:', self.client_address
         lotime = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
         #readline()来获取客户端消息,write()将字符串发回客户端
         self.wfile.write('[%s] %s' % (lotime, self.rfile.readline()))
 
#创建TCP服务器,并无限循环的等待客户端请求
tcpServ = TCP(ADDR, MyRequestHandler)
print 'waiting for conntion....'
tcpServ.serve_forever()

 

客户端:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
#!/use/bin/env python
# -*- coding: utf-8 -*-
 
from socket import *
 
HOST = 'localhost'
PORT = 21567
BUFSIZE = 1024
ADDR = (HOST, PORT)
 
while True:
    tcpCliSock = socket(AF_INET)
    tcpCliSock.connect(ADDR)
    data = raw_input('> ')
    if not data:
        break
    tcpCliSock.send('%s\r\n' % data)
    data = tcpCliSock.recv(BUFSIZE)
    if not data:
        break
    print data.strip()
    tcpCliSock.close()
相关教程