【Python网络编程】【02-1】socket编程之server端

一、socket server端

 1 from socket import *
 2 import hashlib
 3 import os
 4 
 5 HOST = '0.0.0.0'
 6 PORT = 21567
 7 BUFSIZE = 1024
 8 ADDR = (HOST, PORT)
 9 
10 # 1.创建socket实例
11 tcpServerSock = socket(AF_INET, SOCK_STREAM)
12 
13 # 2.实例进行bind连接
14 tcpServerSock.bind(ADDR)
15 
16 # 3.设置监听上限
17 tcpServerSock.listen(5)
18 
19 while True:
20     print("waiting for connection...")
21     # 4.检测新的客户端连接进来,形成新的socket服务端实例
22     tcpCliSock, addr = tcpServerSock.accept()
23     print("New connection from: ", addr)
24 
25     while True:
26         try:
27             data = tcpCliSock.recv(BUFSIZE) # 5.由服务端实例进行接收和发送
28             print('New cmd from client is: ', data.decode('utf-8'))
29             if not data:
30                 print('%s connection broken, bye!' % str(addr))
31                 break
32             data_parse = data.decode("utf-8").split("get ") # 反解码把Byte二进制格式解码为utf-8字符串格式。
33             fileName = data_parse[1]
34             if os.path.exists(fileName):
35                 if os.path.isfile(fileName):
36                     file_size = os.path.getsize(fileName)
37                     tcpCliSock.send(str(file_size).encode()) # 解码为默认Byte二进制格式
38                     tcpCliSock.recv(1024)
39                     m = hashlib.md5()
40                     sendSize = 0
41                     # read 50 Mb each time
42                     chunk_size = 50*1024*1024
43                     f = open(fileName, 'rb')
44                     while True:
45                         data_read = f.read(chunk_size)
46                         if not data_read:
47                             break
48                         m.update(data_read)
49                         tcpCliSock.send(data_read)
50                     f.close()
51                     print("Server file %s send done" % fileName)
52                     # 以下屏蔽的部分是按行读取后进行发送,速度比较慢。
53                     # for line in f:
54                     #     m.update(line)
55                     #     tcpCliSock.send(line)
56                     #     sendSize_this = len(line)
57                     #     sendSize += sendSize_this
58                     #     print("this time sended: ", sendSize_this)
59                     #     print("total size sended: ", sendSize)
60                     tcpCliSock.send(m.hexdigest().encode())
61                 else:
62                     tcpCliSock.send('target is dir, not file'.encode())
63             else:
64                 tcpCliSock.send('no such file'.encode())
65         except ConnectionResetError as e:
66             print('%s connect error, error info: %s' % (addr, e))
67             break
View Code

posted on 2018-02-28 09:22  yingriwuhen  阅读(166)  评论(0)    收藏  举报