使用SocketServer模块(在python3中是socketserver)编写的tcp网络程序示例:
#!/usr/bin/env python
#server
from SocketServer import TCPServer as TCP, StreamRequestHandler as SRH
class MyRequestHandler(SRH):
def handle(self):
print I am server and recved: %s from %s % (self.rfile.readline().strip(), self.client_address)
self.wfile.write(I am server)
tcpServ = TCP((HOST, PORT), MyRequestHandler)
tcpServ.serve_forever()
################################################
#!/usr/bin/env python
#client
from socket import *
while True:
tcpCliSock = socket(AF_INET, SOCK_STREAM)
tcpCliSock.connect((HOST,PORT))
tcpCliSock.send(I am client )
data = tcpCliSock.recv(BUFSIZE)
if not data:
break
print I am client and recved: , data
tcpCliSock.close()
#################################################################
使用SocketServer模块编程的udp网络程序示例:
#!/usr/bin/env python
#server
from SocketServer import DatagramRequestHandler as DRH, UDPServer as UDP
class MyRequestHandler(DRH):
def handle(self):
print I am server and recved: %s from %s % (self.rfile.readline(), self.client_address)
self.wfile.write(I am server)
ss = UDP(('localhost', 6543), MyRequestHandler)
ss.serve_forever()
##############################################################
#!/usr/bin/env python
#client
www.2cto.com
from socket import *
while True:
cs = socket(AF_INET, SOCK_DGRAM)
cs.sendto(I am client, (HOST, PORT))
data, saddr = cs.recvfrom(BUFSIZE)
if not data:
break
print 'I am client and recved: %s from %s' % (data, saddr)
cs.close()