Python Socket Server
½ñÌì×öftpµÄ½çÃæ,×öµÄÏ൱ÓôÃÆ£¬ÅªµÃÐÄÇé¼°Æ䲻ˬ£¬ÔÚÍøÉÏËѵ½ËÀ¶¼²»ÖªµÀ¸ÃÔõô°ì£¬´òËãÃ÷ÌìÏÈ¿´¿´C£«£«
µÄÊÇÔõôŪµÄÔÙ˵¡£²»¹ý£¬ÏÖÔÚÎÒÏëдһϹØÓÚsocketµÄ±à³Ì¡£
ÏÈдһ¸öʱ¼ä·þÎñÆ÷°É£¬Ëû¼àÌý¶Ë¿Ú£¬²¢Çһ᷵»Ø ·þÎñÆ÷µÄʱ¼ä
server.py
#!/usr/bin/python
# Copyright (c) angelipin (angelipin@126.com)
import SocketServer
import time
import logging
__version__ = "1.0.0"
class ServerHandler(SocketServer.BaseRequestHandler):
def setup(self):
logging.info("start thread.")
self.request.settimeout(60)
def finish(self):
self.request.close()
logging.info("end thread.")
def handle(self):
while 1:
try:
dataReceived = self.request.recv(1024)
if not dataReceived:
break
logging.info('Receive data '+dataReceived)
dataSend = time.ctime(time.time())
self.request.send(dataSend)
except socket.timeout:
print "Time out"
logging.error("Time out")
logging.basicConfig(level=logging.DEBUG,format='%(thread)d %(asctime)s %(levelname)s %(message)s',filename='log',filemode='a+')
Server = SocketServer.ThreadingTCPServer(('',8881),ServerHandler)
logging.info('Server start')
Server.serve_forever()
ÓÃÀ´×ö²âÊÔÓõÄclient.py
import socket
remote_host = '127.0.0.1'
remote_port = 8881
send_buf = open('binary','rb').read()
sock = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
sock.connect((remote_host,remote_port))
sock.send(send_buf)
response_data = sock.recv(1024)
print response_data
sock.close()
Ëæ±ãÔÚbinaryÎļþÀïÃæдµã¶«Î÷ »òÕß ÄãÖ±½Ó»»³É¡£¡£¡£¶Ô°É
²âÊÔ ÏÈÆô¶¯ server
È»ºóÔËÐм¸¸öclient¿´¿´
while true;
do
python client.py;
done;
ÄãÒ²¿ÉÒÔд¸ö¶àÏ̵߳IJâÊÔ¡£ÏñÎÒÕâÑùµÄ¾ÍÊǶ࿪¼¸¸öshell¶¼ÔËÐÐÉÏÃæµÄ´úÂë¡£°¦£¬Ôõô½áÊøÄØ£¿
Ïà¹ØÎĵµ£º
Ô´´úÂëÏÂÔØ£ºÏÂÔصØÖ·ÔÚÕâÀï
# 032
# ÆäʵcPickleÕâ¸öÄ£¿éÆðµ½µÄ×÷ÓÿÉÒÔÓÓÍêÃÀµØе÷ÁËÎļþÖеÄÄÚÈÝ£¨¶ÔÏ󣩺ʹúÂëÖеÄÒýÓÔÀ´ÐÎÈÝ
import cPickle as p # ÕâÌõÓï¾ä¸øcPickleÆðÁ˸öСÃûp
objectFileName = r'C:\Data.txt'
aList = [1, 2, 3]
f = file(objectFileName, 'w')
p.dump(aList, f)
f.close ......
Ô´´úÂëÏÂÔØ£ºÏÂÔصØÖ·ÔÚÕâÀï
raiseÓÐÁ½¸ö²ÎÊý£¬µÚÒ»¸öÊÇÓÉÎÒÃÇ×Ô¼º¶¨ÒåµÄÒì³£ÀàÐÍ£¬µÚ¶þ¸öÊǹØÓÚ´ËÒì³£µÄÉÙÁ¿ËµÃ÷ÐÅÏ¢¡£
# 038
def getAge():
age = input('Input your age:')
if (age < 0 or age > 160):
raise 'BadAgeError', 'It is impossible!!!!!'
# end of if
return age
# ......
µÚ¾Å¹Ø Image
´ÓÒ³ÃæÉϵÄͼƬ¿ÉÒÔ¿´µ½ÓÐÒ»´®µã£¬ÄÇôÊDz»ÊÇ´ú±í¸Ã¹ØÓëͼÏñµãÓйأ¿ ÎÒÃÇ´ÓÒ³ÃæÔ´Âë¿ÉÒÔ¿´µ½£¬ÓÐÁ½¶ÎÊý×ÖÐòÁÐfirstºÍsecond£¬¶øÓÐÒ»¸öÌáʾfirst+second=? ʲôÒâ˼ÄØ£¿ÄѵÀÊÇ˵(first, second)´ú±íÁËͼÏñµãµÄ×ø±ê£¿²»Ïñ£¬Á½¶ÎÐòÁеij¤¶ÈÓкܴó²îÒì¡£ÄÇôËã·û+»¹ÓÐʲôº¬ÒåÄØ£¬Óп ......
ÑéÖ¤ÊÇ·ñÒѾ°²×°ÁËMySQLdb£º
==========================================================
d:\usr\local\Python25>python
Python 2.5.4 (r254:67916, Dec 23 2008, 15:10:54) [MSC v.1310 32 bit (Intel)] onwin32
Type "help", "copyright", "credits" or "license" for ......