2020-01-17 tcp传输

tcp客户端

#! /usr/bin/env python
# -*- coding: utf-8 -*-
# __author__ = "ryan"
# Date: 2020/1/16

import socket

def main():
   #1.创建套接字
   tcp_socket = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
   #2.连接服务器
   dest_ip = '192.168.5.1'
   dest_port = 8080
   tcp_socket.connect((dest_ip,dest_port))
   #3.向服务器发送要下载的文件名称
   file_name = '我的文件.txt'
   tcp_socket.send(file_name.encode('gbk'))
   #4.接收从服务器发送来的文件数据
   recv_data = tcp_socket.recv(1024)
   if recv_data:
       with open('[接收]'+file_name,'wb') as f:
           f.write(recv_data)
   tcp_socket.close()
if __name__ == '__main__':
   main()

tcp_服务器

#! /usr/bin/env python
# -*- coding: utf-8 -*-
# __author__ = "ryan"
# Date: 2020/1/16

import socket

def main():
    #1.创建套接字
    tcp_socket = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
    #2.绑定端口
    dest_ip = '192.168.5.1'
    dest_port = 8080
    tcp_socket.bind((dest_ip,dest_port))
    #3.收到客户端发来的要下载的文件名
    tcp_socket.listen(128)
    client_socket,client_addr = tcp_socket.accept()
    file_name = client_socket.recv(1024).decode('gbk')
    #4.接收从服务器发送来的文件数据
    file_content = None
    if file_name:
        try:
            f = open(file_name,'rb')
            file_content = f.read()
            f.close()
        except Exception as ret:
            print("没有要下载的文件{}".format(file_name))
    if file_content:
        client_socket.send(file_content)
    client_socket.close()
    tcp_socket.close()
if __name__ == '__main__':
    main()

你可能感兴趣的:(2020-01-17 tcp传输)