文件上传
#服务端
while True:
conn,address = sk.accept()
conn.sendall(bytes('欢迎你小sb',encoding='utf-8'))
str_size = str(conn.recv(1024),encoding='utf-8')
int_size = int(str_size)
print(int_size)
#创建文件
f = open('new.jpg','wb')
has_recv = 0
#接受文件
while True:
if has_recv == int_size:
break
else:
date = conn.recv(1024)
f.write(date)
has_recv += len(date)
f.close()
#客户端
import socket
import os
obj = socket.socket()
obj.connect(('127.1.1.1',9999,))
ret_bytes = obj.recv(1024)
print(str(ret_bytes,encoding='utf-8'))
#发送文件大小
size = os.stat('tp.jpg').st_size
obj.sendall(bytes(str(size),encoding='utf-8'))
#发送文件
with open('tp.jpg','rb') as f:
for i in f:
obj.sendall(i)
obj.close()
ThreadingTCPServer
服务端
import socketserver
class MyServer(socketserver.BaseRequestHandler):
def handle(self):
conn = self.request
conn.sendall(bytes('hello小sb',encoding='utf-8'))
print(1)
if __name__ == '__main__':
server = socketserver.ThreadingTCPServer(('127.1.1.1',9999), MyServer)
server.serve_forever()
客户端
import socket
obj = socket.socket()
obj.connect(('127.1.1.1',9999,))
ret_bytes = obj.recv(1024)
print(str(ret_bytes,encoding='utf-8'))
obj.close()