首页 > 代码库 > python网络编程(一)

python网络编程(一)

python网络编程(一)。

功能:客户端向服务器发送一张图片。

服务器代码:

 1 #!/user/bin/env python
 2 # -*- coding:utf-8 -*-
 3 import socket
 4 sk = socket.socket()
 5 sk.bind((127.0.0.1, 8080, ))
 6 sk.listen(5)
 7 while True:
 8     conn, address = sk.accept()
 9     conn.sendall(bytes(欢迎登陆FTP!, encoding=utf-8))
10     file_size = conn.recv(1024).decode()
11     conn.sendall(bytes(已收到!, encoding=utf-8))
12     total_size = int(file_size)
13     print(file_size)
14     has_recv = 0
15     f = open(2.jpg, wb)
16     while True:
17         if total_size == has_recv:
18             break
19         else:
20             data = http://www.mamicode.com/conn.recv(1024)
21             f.write(data)
22             has_recv += len(data)
23     f.close()

客户端代码:

#!/user/bin/env python
# -*- coding:utf-8 -*-
import socket
import os
obj = socket.socket()
obj.connect((127.0.0.1, 8080, ))
ret_bytes = obj.recv(1024)
ret_str = str(ret_bytes, encoding=utf-8)
print(ret_str)
size = os.stat(1.jpg).st_size
obj.sendall(bytes(str(size), encoding=utf-8))
obj.recv(1024)
with open(1.jpg, rb) as f:
    for line in f:
        obj.sendall(line)
obj.close()

 

python网络编程(一)