一、伺服器端**
#!/usr/bin/env python
#-*- coding:utf-8 -*-
#environment:2.7
#在python3中,模組不是socketserver,而是socketserver
import os,json,time,socketserver,threading
file_path = '/root/update/123.txt'
deftake_hander
(file_path,code='utf-8'):
''' 這個函式是用來生成檔案頭以及對檔案的處理
:param file_path:
:param code:
:return:
'''file_name_list = file_path.rsplit(os.sep,1)
if len(file_name_list) > 1:
file_name = file_name_list[1]
else:
file_name = file_path
file_size = os.path.getsize(file_path)
date = time.strftime('%y-%m-%d %x',time.localtime())
head_data =
file_head = json.dumps(head_data)
return file_head
#設定socketserver的handle
class
myhandler
(socketserver.baserequesthandler):
defsetup
(self):
#類似於建構函式,setup不可用接收引數
self.file = open(file_path,'r')
self.content = self.file.read()
self.file_head = take_hander(file_path)
defhandle
(self):
#self.client_address 是模組類當中以及設定好的儲存client的ip和埠
#self.request是模組類中已經設定好的接收和傳送資訊的物件,是乙個socker物件
print('%s:%s is connected' % self.client_address)
request_data = self.request.recv(1024)
print(request_data)
self.request.send(self.file_head) #把頭部內容傳送過去
request_data1 = self.request.recv(1024)
print(request_data1)
self.request.sendall(self.content) #傳送檔案內容
deffinish
(self):
#類似於類中的析構函式
print('%s is done' %self.file)
if self.file.closed == false:
self.file.close()
#通過多繼承形成新的支援多執行緒伺服器
class
myserver
(socketserver.tcpserver,socketserver.threadingmixin):
pass
if __name__ == '__main__':
ip_port = ('127.0.0.1',9600)
m = myserver(ip_port,myhandler)
p = threading.thread(target=m.serve_forever,args=())
p.start()
#m.shutdown()
#m.server_close()
二、客戶端**
#!/usr/bin/env python
#-*- coding:utf-8 -*-
#environment:2.7
import socket,json
while true:
sk = socket.socket(socket.af_inet,socket.sock_stream)
ip_port = ('127.0.0.1',9600)
sk.connect(ip_port)
user_input = raw_input('>>>:').strip()
iflen(user_input) == 0:continue
if user_input == 'q':break
sk.send(user_input)
server_head_msg = json.loads(sk.recv(1024))
print(server_head_msg)
#檔名res_name,檔案大小res_size
res_name = server_head_msg['file_name']
res_size = server_head_msg['file_size']
sk.send('已經收到頭部資訊,可以傳送資料了')
num = res_size/256.0
ifnum != int(num):
num = int(num) +1
else:
num = int(num)
for i in range(num):
content = sk.recv(1024)
print(content)
python socket簡單使用 一
匯入socket模組 import socket socket可以看做為乙個檔案,用乙個socket表示 開啟了乙個網路鏈結 開啟乙個socket需要知道目標計算機的ip位址和埠號 建立tcp連線是,自動發起連線的叫做客戶端,被動響應連線的叫做伺服器 新建乙個socket物件 原型 socket.s...
Python Socket 程式設計
client import socket,sys if name main 處理引數 argv sys.argv if len argv 3 or len argv 2 and argv 1 print useage argv 0 sys.exit 0 host argv 1 server ip位址...
python socket程式設計
python 編寫server的步驟 1.第一步是建立socket物件。呼叫socket建構函式。如 socket socket.socket family,type family引數代表位址家族,可為af inet或af unix。af inet家族包括internet位址,af unix家族用於...