You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
teamwk123/python/tcpserver.py

83 lines
1.7 KiB

# @Coding: utf-8
# @Time: 2021/8/3 3:13
import socket
import os
HOST = "0.0.0.0"
PORT = 8181
so = socket.socket(socket.AF_INET, socket.SOCK_STREAM)# 建立Socket连接, AF_INEF说明使用IPv4地址, SOCK_STREAM指明TCP协议
so.bind((HOST, PORT))# 绑定IP和端口
so.listen(1)# 监听
#print(f"listen: {so.listen(1)} connected")
conn, addr = so.accept()# 接收TCP连接, 并返回新的Socket对象
#print(f"Client: {addr} connected")# 打印客户端的IP
message = "Connection Success"
conn.send(message.encode('utf8'))# 向客户端发送当前的时间, send()函数接收的参数为bytes类型,
#data = conn.recv(1024).decode()# 接收客户端发送的数据
#data1 = conn.recv(1024)# 接收客户端发送的数据
#print(data1)
#l=data.split(' ')
#step1:username
d1=conn.recv(1024)
#l1=data1.split(b' ')
l1=d1.split(b' ')
print(l1)
username=l1[1].decode()
print('username:',username)
if os.path.exists('web//'+username):
pass
else:
os.mkdir('web//'+username)
conn.send(b'username')
#step2:filename
d2=conn.recv(1024)
l2=d2.split(b' ')
filename = l2[1].decode()
#conn.send(b'filename')
print('filename:',filename)
conn.send(b'filename')
#step3:filesize
d3=conn.recv(1024)
l3=d3.split(b' ')
filesize=int(l3[1].decode())
#conn.send(b'filesize')
print('filesize:',filesize)
conn.send(b'filesize')
#step4:content
recvsize=0
f=open('web//'+username+'//'+filename,'wb')
while recvsize<filesize:
size = 0
if filesize-recvsize>1024:
size=1024
else:
size=filesize-recvsize
data=conn.recv(size)
datalen=len(data)
recvsize+=datalen
f.write(data)
#content1=l1[7]
#print('content:',content1)
f.close()
print("recvsize:",str(recvsize))
#f.close()
conn.close()# 关闭连接
'''
f.write(content1)
f.close()
'''