服务端代码
import socket
# 创建tcp服务套接字
def main():
tcp_server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
tcp_server_socket_for_file_name = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
print("1.套接字创建完毕...")
# 绑定端口号
tcp_server_socket.bind(("",40000))
tcp_server_socket_for_file_name.bind(("",50000))
print("2.端口绑定完毕")
# 转为被动模式
tcp_server_socket.listen(128)
tcp_server_socket_for_file_name.listen(128)
print("3.被动模式转换完毕")
# 接收到新的连接则创建服务套接字
client_socket, client_addr = tcp_server_socket.accept()
client_socket_for_file_name, client_addr_for_file_name = tcp_server_socket_for_file_name.accept()
print("4.拆包完毕....")
file_name = client_socket_for_file_name.recv(1024)
print("接收到的file_name为:%s"%file_name)
file_name = file_name.decode("utf-8")
f = open(file_name,"wb+")
while True:
content = client_socket.recv(50)
if (content):
print("准备写入",content)
f.write(content)
print("已经写入",content)
else:
f.close()
break
print("执行完成")
if __name__ == "__main__":
main()
客户端代码
import socket
import os
g_the_dir_list = list()
# 显示目录
def display_dir():
print("当前目录为:")
for i, the_dir in enumerate(g_the_dir_list):
print(i, the_dir)
def main():
global g_the_dir_list
# 读取当前目录下文件列表
g_the_dir_list = os.listdir(os.getcwd())
# 创建客户端socket
client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# 创建第二个socket(负责发送文件名)
client_socket_for_file_name = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# 建立连接
server_ip = input("请输入服务端ip(占用端口40000与50000)")
client_socket.connect((server_ip, 40000))
client_socket_for_file_name.connect((server_ip, 50000))
# 显示当前目录下文件列表
display_dir()
file_index = int(input("请输入需要传送的文件序号:"))
# 打开文件并通过socket.send发送
client_socket_for_file_name.send(g_the_dir_list[file_index].encode("utf-8"))
f = open(g_the_dir_list[file_index], "rb")
while True:
content = f.read(1024)
if (content):
client_socket.send(content)
else:
print("发送完毕!")
f.close()
break
if __name__ == "__main__":
main()