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¶¼ÔËÐÐÉÏÃæµÄ´úÂë¡£°¦£¬Ôõô½áÊøÄØ£¿
Ïà¹ØÎĵµ£º
Ô´´úÂëÏÂÔØ£ºÏÂÔصØÖ·ÔÚÕâÀï
e.g.1
# 030
aFile = file(r'C:\temp.txt', 'a')
aFile.write('ÓÖÌí¼ÓÁËÒ»ÐС£')
aFile.close()
output:
e.g.2
# 030
aFile = file(r'C:\temp.txt', 'a')
aFile.write('ÓÖÌí¼ÓÁËÒ»ÐС£')
aFile.close()
output:
e.g.3
ʵÏÖ¸ù¾ÝÔʼÎļþÓÐûÓÐ×îºóÒ»ÐпÕÐеÄÇé¿öÀ´½øÐÐ&ldqu ......
Ô´´úÂëÏÂÔØ£ºÏÂÔصØÖ·ÔÚÕâÀï
# 033
class Person:
age = 22
def sayHello(self): # ·½·¨Ó뺯ÊýµÄÇø±ðÔÚÓÚÐèÒªÒ»¸öself²ÎÊý
print 'Hello!'
# end of def
# end of class # ÕâÊÇÎÒÁ¼ºÃµÄ±à³Ì·ç¸ñ
p = Person()
print p.age
p.sayHello()
output£º
22
Hello! ......
µÚ¾Å¹Ø Image
´ÓÒ³ÃæÉϵÄͼƬ¿ÉÒÔ¿´µ½ÓÐÒ»´®µã£¬ÄÇôÊDz»ÊÇ´ú±í¸Ã¹ØÓëͼÏñµãÓйأ¿ ÎÒÃÇ´ÓÒ³ÃæÔ´Âë¿ÉÒÔ¿´µ½£¬ÓÐÁ½¶ÎÊý×ÖÐòÁÐfirstºÍsecond£¬¶øÓÐÒ»¸öÌáʾfirst+second=? ʲôÒâ˼ÄØ£¿ÄѵÀÊÇ˵(first, second)´ú±íÁËͼÏñµãµÄ×ø±ê£¿²»Ïñ£¬Á½¶ÎÐòÁеij¤¶ÈÓкܴó²îÒì¡£ÄÇôËã·û+»¹ÓÐʲôº¬ÒåÄØ£¬Óп ......
filename=raw_input('enter file name:')
f=open(filename,'rb')
f.seek(0,0)
index=0
for i in range(0,16):
print "%3s" % hex(i) ,
print
for i in range(0,16):
print "%-3s" % "#" ,
print
while True:
temp=f.read(1)
if len(temp) == 0:
break
else:
print "%3s" % temp.encode('hex'),
......